Jan 9, 2014 at 3:51pm UTC
I know it's a basic question, but, can you please tell me how can I take the nearest integer of a floating variable? For example, if C=1.25, I want to take Cint=1; if C=1.5, Cint=2, and so on. Also, I want to secure that it works with negative numbers as well.
Jan 9, 2014 at 4:00pm UTC
Thanks, DTScode, but I'm having these problems:
It gives this warning:
[Warning] converting to 'int' from 'double'
It still compiles, but the double number is only rounded down, never up. 3.2 and 3.999 return 3.
Further, when I try to enter the floating value myself with cin, it returns 0.
Last edited on Jan 9, 2014 at 4:01pm UTC
Jan 9, 2014 at 4:01pm UTC
Last edited on Jan 9, 2014 at 4:41pm UTC
Jan 9, 2014 at 4:06pm UTC
you can just add an If statment like this (relying on previous response) :
1 2
if (mydub>myint+0.5)
myint=myint+1;
dont forget u can do this only after the casting.
Last edited on Jan 9, 2014 at 4:07pm UTC
Jan 9, 2014 at 4:31pm UTC
This isn't working, it returns errors. This "return floor" seems to be making some mess, the prompt only blinks at the screen. I'm trying this:
1 2 3 4 5 6 7 8 9 10 11 12
int main () {
double d=5.6;
double round(double d);
{
double neg = d < 0 ? -1 : 1;
return floor(d + (neg * 0.5));
}
system ("PAUSE" );
return 0;
}
Last edited on Jan 9, 2014 at 4:31pm UTC
Jan 9, 2014 at 4:37pm UTC
Why did you declare the function inside main? Also the code I posted is updated and one more link included which contains a link to the official round function for c++
Jan 9, 2014 at 4:47pm UTC
Smac89, where shall I declare the function? If before main, it returns
expected unqualified-id before '{' token
expected `,' or `;' before '{' token
How can I know if my version of C++ is more recent than 11?
Jan 9, 2014 at 5:00pm UTC
The most recent version of c++ (to my knowledge) is c++14, but you just need c++11 for this.
If you are using an IDE, you will have to check the website for the specific IDE to see if the current version supports c++11.
If you use a terminal, try compiling the program with the flag -std=c++11 or -std=gnu++11
Declare the function before main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <cmath>
#include <iostream>
double round(double d)
{
return d < 0 ? ceil(d - 0.5) : floor(d + 0.5);
}
int main()
{
double d = 3.75;
cout << round(d) << endl;
return 0;
}
Last edited on Jan 9, 2014 at 5:06pm UTC
Jan 9, 2014 at 5:15pm UTC
Thanks a lot, Smac89. It's working perfectly now!