• Create Account

## C++ % Operator Problem

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

6 replies to this topic

### #1Youbar  Members

Posted 12 October 2012 - 10:53 PM

Hi, I'm just starting out C++ and decided to have an attempt at making a calculator, probably very crude but it works. Anyway, I'm having a problem with the % operator. This is only a portion of my code, but you'll get the gist:

else if(response == 5) {
cout << "Remainder" << endl;
cout << "Enter first number: ";
cin >> fn;
cout << "Enter second number to divide and get remainder: ";
cin >> sn;
float ovrl = (fn % sn);
cout << ovrl << endl;
system("PAUSE");
goto startagain;
}

The code returns this error:
invalid operands of types float' and float' to binary operator%'

Full code here:
Spoiler

### #2MrMonkeh  Members

Posted 12 October 2012 - 11:02 PM

I believe the modulus operator (%) only works with integer types. You'll have to convert fn and sn to integer if you want to use it.

Or...a quick search on google and I stumbled upon "fmod". Used like so:
fmod(5.5, 3.5) // takes numerator and denominator

Note: I've never used this function before, so no promises. Though I believe you need to include the math header file to use fmod.

### #3Youbar  Members

Posted 12 October 2012 - 11:08 PM

I don't understand the fmod function...but about the converting fn and sn to integers...wouldn't that remove the decimals and round it down?
e.g 1.2 % 5 would return 0.

Edited by Youbar, 12 October 2012 - 11:18 PM.

### #4RulerOfNothing  Members

Posted 12 October 2012 - 11:49 PM

fmod is simply a floating point version of the modulus operator. It takes two arguments (the numerator and denominator, in that order) and calculates the remainder like so:
remainder = numerator - quotient * denominator where quotient is an integer and the remainder is less than the denominator.
For example fmod(5.5,3.5) would return 2.

### #5Youbar  Members

Posted 13 October 2012 - 12:04 AM

Could you give me an example of how I would apply it to my script please? It's returning errors.
Thanks.

### #6L. Spiro  Members

Posted 13 October 2012 - 12:17 AM

float ovrl = fmodf(fn, sn);`

L. Spiro

### #7Youbar  Members

Posted 13 October 2012 - 12:32 AM

Thanks, problem solved.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.