Doing an exercise from my C++ book and got asked to create a program that takes a double value and using a function rounds it to nearest whole value. I made my program, go the ambiguous error, so checked their code and mine happened to be more or less the same bar a few variable names, and i tried theirs and got the same problem.
#include <iostream>
#include <cmath>
usingnamespace std;
void round(double &i);
int main()
{
double i = 0.0;
cout << "Please enter a decimal number: ";
cin >> i;
cin.ignore();
cout << "\n\n'i' rounded to the nearest value is ";
round(i);
cout << i;
cin.get();
return 0;
}
void round(double &i)
{
double fractpart = 0.0; intpart = 0.0;
fractpart = modf(i, &intpart)
if(fractpart<0.5) i = intpart;
else intpart+=1.0;
}
I don't understand why though because there's only one function so its not like i'm overloading incorrectly. And 'i' is double like the function requires.
The error message says:
9 C:\Users\alan\Desktop\trial.cpp call of overloaded `round(double&)' is ambiguous
note C:\Dev-Cpp\include\math.h:672 candidates are: double round(double)
note C:\Dev-Cpp\include\math.h:672 void round(double&)
1. intpart has no type declared. You need to put int intpart = 0.0;
2. You're missing a semicolon at the end of this line fractpart = modf(i, &intpart)
Thats quite poor tbh though with the book because thats the second time this has happened. The last time was with the variable 'count' - apparently something already in the std namespace that is called 'count. I was under the impression Herbert Schildt was one of the top programmers.
Edit: Then again maybe i'm being too harsh on possibly 'simple' mistakes. Afterall, the book is actually vary good and for such a vast amount of examples and explanations, errors are likely to occur.
ya but note that these functions don't round the number,so ceil(.4) would return 1 and floor(.6) would return 0.
You could right a function to make these work, but i find it easier just to cast the number. Either way is fine though
I meant they dont round up if not greater then 1, so ceil(.4) = 1. But Grey wolf , some how i forgot about the existance of negitive numbers lol
here :
1 2 3 4 5 6 7 8 9
double num, x = .5;
int round;
cin>>num;
if(num<0)
x = -.5;
round = static_cast<int>(num + x);
cout<<round<<endl;
seem easier then writing conditions for ceil and floor.. my opinion