Need help with loops
Feb 6, 2015 at 2:05am UTC
Cant get my program to loop correctly and i just cant figure it out.
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
#include <iostream>
using namespace std;
void avgTwoNumbers(double M, double F);
void checkNumbers(double someNum);
void setNumbers();
double num1, num2;
char check = 'Y' ;
char repeat = 'Y' ;
int main()
{
char repeat = 'y' ;
while ( repeat == 'y' || repeat == 'y' )
setNumbers();
avgTwoNumbers(num1, num2);
system("PAUSE" );
return 0;
}
void avgTwoNumbers(double M, double F)
{
double total = (M + F)/2;
cout << "your average grade is " << total << endl;
}
void checkNumbers(double someNum)
{
if (someNum < 0 || someNum > 100)
{
cout << " Number must be between 0 and 100" << endl;
}
else
check = 'N' ;
}
void setNumbers()
{
while (check == 'Y' )
{
cout << "Enter the Midterm grade: " ;
cin >> num1;
checkNumbers(num1);
}
check = 'Y' ;
while (check == 'Y' )
{
cout << "Enter the Final grade: " ;
cin >> num2;
checkNumbers(num2);
}
cout << "Repeat? Y/N" << endl;
cin >> repeat;
}
Feb 6, 2015 at 2:47am UTC
what can't you figure out?
1 2 3
char repeat = 'y' ;
while ( repeat == 'y' || repeat == 'y' )
your loop will always be true but even if it wasn't your code will never run.
Last edited on Feb 6, 2015 at 2:58am UTC
Feb 6, 2015 at 3:37am UTC
- Use do-while loops
- Have the functions return values.
- Make sure your indentation matches the structure of the code. For example, your code executes only one statement (line 31) inside the loop at line 26.
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
using namespace std;
void avgTwoNumbers(double M, double F);
bool checkNumbers(double someNum);
void setNumbers();
double num1, num2;
int
main()
{
char repeat;
do {
setNumbers();
avgTwoNumbers(num1, num2);
cout << "Repeat? Y/N" << endl;
cin >> repeat;
} while (repeat == 'Y' );
return 0;
}
void
avgTwoNumbers(double M, double F)
{
double total = (M + F) / 2;
cout << "your average grade is " << total << endl;
}
bool
checkNumbers(double someNum)
{
if (someNum < 0 || someNum > 100) {
cout << " Number must be between 0 and 100" << endl;
return false ;
} else {
return true ;
}
}
void
setNumbers()
{
do {
cout << "Enter the Midterm grade: " ;
cin >> num1;
} while (!checkNumbers(num1));
do {
cout << "Enter the Final grade: " ;
cin >> num2;
} while (!checkNumbers(num2));
}
Topic archived. No new replies allowed.