tags:

views:

170

answers:

5

Hey all, my names joe and im running into a few issues with the modulus in c++

heres the problem:

#include <iostream>
#include <string> 
using namespace std;

int main()
{
//In short, this is what i am trying to do:
//divide two numbers, and get both the quotient
//and the remainder
//however, as an example, this below produces a remainder
//of 10 
//110 \ 20 should equal 5 remainder 5
int firstInput =110, secondInput = 20;

int quotient = 0, remainder = 0;

quotient = firstInput / secondInput;

remainder = firstInput % secondInput;// i think the problem is here

cout << "The quotient is " << quotient << " and the remainder is "
    << remainder << endl;


system("pause");
return 0; 
}

basically its not computing the remainder correctly. any help of course would be much appreciated. cheers

+1  A: 

110 = 5*20 + 10

the remainder is 10, not 5

second
Thanks, i feel kinda embarrassed now, but thanks again otherwise I would have never figured this out.
Joseph
+7  A: 

I get the correct answer...

The quotient is 5 and the remainder is 10
Press any key to continue . . .  

I think the bug is probably located between the keyboard and the chair ... =P

James
Haha so true, well at least you put a smile on my face, man I need to brush up on my math I think, or something, cheers :)
Joseph
Happens to the best of us. =D
James
+1  A: 

110 = 5 * 20 + 10, therefore the quotient is 5, and remainder is 10. So it seems to calculate correctly.

If you want to get the "rest" 0.5, you need to calculate ((double)firstInput/secondInput) - (firstInput/secondInput).

Vlad
Looks like i was getting rest confused with remainders, thanks for the rest code too, man its been a long day.
Joseph
not a problem, hope our answers help
Vlad
A: 

If you divide 110 by 20, you should get a quotient of 5 and a remainder of 10... because:

5*20 + 10 = 110
Martin B
This makes so much sense, cheers
Joseph
A: 

try fmod to get what you want.

-1 unclear and rather useless advice
Tomas
From http://www.cppreference.com/wiki/c/math/fmodThe fmod() function returns the remainder of x/y. #include <cmath> double fmod( double x, double y );Better?