|
||
|
|
#1 (permalink) |
|
Master of the Internet
|
Code:
#include <iostream>
using namespace std;
int main()
{
int q, c;
double tunumber, i;
cout<<"Enter the number you are too stupid to round.\n";
cin>>tunumber;
i = tunumber % 1;
if( i <= 5 )
{
c = tunumber;
}
else
{
c = ++tunumber;
}
cout<<c;
cin>>q;
return 0;
}
10 C:\Documents and Settings\zachary maynard\Desktop\assignment1.cpp invalid operands of types `double' and `int' to binary `operator%' But it is the same if I use 1.0. Why can't I use % with doubles? Last edited by DontdroptheSOAD; 12-30-2005 at 02:24 AM. |
|
|
|
|
|
#2 (permalink) |
|
Forum Expert
|
Because the modulus operation using '%' is defined only for types convertible to an integer type (note that I say integer and not 'int' as I'm referring to that class of types and not strictly to 'int'). This is why fmod() and other associated functions were defined, to do different kind of floating-point modulus operations on types that the '%' operator does not support.
Though this is still not what you're looking for (I would like to know what gave you the impression that taking the [integer] remainder of the division of a real number with 1 would give the number rounded, at best it would return the integer version of the value [i.e. the number with its fractional component truncated]) as you're trying to do somethind that fmod() would not help you with. Look for another, simpler, way of rounding to get this done. As to why modulus operations aren't supported using normal operands, finding the remainder of a floating-point division is not normally relevent, especially when taking into account the wide range of values that need to be accounted for and is almost solely used when concerning integers, i.e. it is not a necessity to have that functionality inherent in the standard operators considering it's usefulness, therefore it's relegated to a function in the standard library if its use is needed. |
|
|
|
|
|
#3 (permalink) |
|
Administrator
Join Date: Aug 2002
Location: Baltimore, MD
Age: 25
Posts: 4,864
|
easy way to round:
Code:
double Round( double num )
{
return (double)((int)(num + 0.5));
}
Also, you usually can't use ++ on non-integral types either. (But this may be compiler dependant)
__________________
Zippy, Razor Creator and RunUO Core Developer The RunUO Software Team "Intuition, like a flash of lightning, lasts only for a second. It generally comes when one is tormented by a difficult decipherment and when one reviews in his mind the fruitless experiments already tried. Suddenly the light breaks through and one finds after a few minutes what previous days of labor were unable to reveal." ~The Cryptonomicon |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|