RunUO Community

This is a sample guest message. Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, as well as connect with other members through your own private inbox!

Rounding.

Maynza

Formerly DontdroptheSOAD
Rounding.

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;
}

Won't compile because:
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?
 

Sep102

Page
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.
 

Zippy

Razor Creator
easy way to round:

Code:
double Round( double num )
{
    return (double)((int)(num + 0.5));
}

Sep102 is right about everything he said.

Also, you usually can't use ++ on non-integral types either. (But this may be compiler dependant)
 
Top