0

Im having problems with this code. At the end numNickels is supposed to have the value of 1 but it keeps giving me a value of 0. I dont know why. Please help.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main(){
int numQuarters;
int numDimes;
int numNickels;
int numPennies;

numQuarters= ((1.15/0.25)-(fmod(1.15,0.25)/0.25));
cout << "1 is " << (1.15/0.25) << endl; 
cout << "2 is " << (fmod(1.15,0.25)/0.25) << endl;  
cout << "The number of quarters is: " << numQuarters << endl;

double d= fmod(1.15,0.25);
numDimes= ((d/0.1)-(fmod(d,0.1)/0.1));
cout << "1 is " << (d/0.1) << endl; 
cout << "2 is " << (fmod(d,0.1)/0.1) << endl;
cout << "The number of dimes is: " <<numDimes << endl;

double n= fmod(d,0.1);
numNickels= n/0.05;

cout << "The " << n << endl;

cout << "The number of nickels is: " << numNickels << endl;
}
  • You do a lot of floating point arithmetic using `double` values and functions. Then you store the result in *integer* variables? Is that by purpose? – Some programmer dude Jul 07 '18 at 16:36
  • Yeah, but when they are stored in integer variables they already have become integers. – Sebastian Madera Jul 07 '18 at 16:38
  • Floating point arithmetic is approximate and introduces errors. Before converting to integer, the value of `n/0.05` is `0.99999999999999811262` – Barmar Jul 07 '18 at 16:38
  • Floating point arithmetic will (as explained in the duplicate) lead to rounding errors, so your valie which you think is `1` is not *really* exactly equal to `0`. So when you assign to an `int` variable the imprecise values is not rounded up to `1` but *truncated* to `0`. – Some programmer dude Jul 07 '18 at 16:41
  • Hmmm. I see, thanks to all of you. – Sebastian Madera Jul 07 '18 at 16:46

0 Answers0