While Loop with division
Oct 20, 2016 at 4:27pm UTC
I'm having issues with the division section of my code. When I run the code for the decimal(answer) I'm getting 1.00 across the board. When user enters the number 5 the code is suppose to print:
Please enter a number between 5 and 12: 5
1/1 is 1.00
1/2 is 0.50
1/3 is 0.33
1/4 is 0.25
1/5 is 0.20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float answer = 0.00;
int userNum = 0;
int count = 1;
cout << "Please enter a number between 5 and 12: " ;
cin >> userNum;
cout << userNum << endl;
if ((userNum < 5) || (userNum > 12)) {
cout << "Please follow directions!" << endl;
count = userNum + 1;
}
while (count < userNum) {
answer = (1 / count) + (1 % count);
cout << "1/" << count << " is " ;
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << answer;
cout << endl;
count++;
}
return 0;
}
Oct 20, 2016 at 4:34pm UTC
What do you try to achieve on line 20?
Integer division produces integer:
1/1 + 1%1 = 1 + 0 = 1
1/2 + 1%2 = 0 + 1 = 1
1/3 + 1%3 = 0 + 1 = 1
1/4 + 1%4 = 0 + 1 = 1
On the other hand
(1.0 / count)
is a floating point division.
Topic archived. No new replies allowed.