1 is an integer so the compiler returns the result as an integer. Therefore you need to do a cast. 1.0 will work or (float) 1/num or in c++ static_cast<float>(1)/num.
okay, so I did change 1/num to 1.0/num, and that fixed that. but this output
CSCE 1020 Lab 9 Randall Hall randallhall2@my.unt.edu
Enter an even number: -6
The number is not a positive even number.
Enter an even number: 0
The number is not a positive even number.
Enter an even number: 23
The number is not a positive even number.
Enter an even number: 4
The number 4 is even!
/*
Randall Hall
CSCE 1020.302
Lab 09
randallhall2@my.unt.edu
*/
#include <iostream>
int main() {
float val, sum, incr;
int num;
cout << "CSCE 1020 Lab 9\tRandall Hall\trandallhall2@my.unt.edu" << endl;
cout << "\n";
do {
cout << "Enter an even number: ";
cin >> num;
if(num % 2 == 0 && num > 0 && num != 0)
cout << "The number " << num << " is even!" << endl << endl;
else
cout << "The number is not a positive even number." << endl;
} while (num % 2 !=0 || num <=0);
sum = 0;
incr = 1.0/(float)num;
do {
cout << val << " ";
sum += val;
val += incr;
} while (val < 21.0 && val > 20.0); //if I do ||, it sends me back into an infinite loop
cout << "" << endl;
cout << "The sum is " << sum << endl;
return 0;
}
You should always initialize your variables. Some formatting would be nice, too.
It would also help commenting your code. What is it supposed to do?
// val is something, nobody knows
do{
// something is printed
cout << val << " ";
// something is added to sum (initially zero)
sum += val;
// something is increased by something else
val += incr;
// the loop lasts if something is smaller
// than 21 AND larger than 20 between 20 and 21
// (20.0 < val && val < 21.0)
} while (val < 21.0 && val > 20.0);
With || the loop will last if something is smaller than 21 OR larger than 20 that is pretty much every possible number so it will never quit (val < 21.0 || 20.0 > val)