So I have this exercise, I need to ask the user for 2 inputs (grades >0 <10) and then I have to print the average and then ask the user if they want to insert more grades 1-yes 2-no; if it's 1 then the program runs again, if it's 2 the program quits. But I'm having trouble to make the program quit.
// ConsoleApplication7.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include "stdafx.h"
int main()
{
using namespace std;
float n1;
float n2;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
int g;
cin >> g;
if (g = 1) {
main();
}
else if (g = 2) {
return 0;
}
}
return 0;
}
答案 0 :(得分:5)
The problem is to test for equality you need two =
, not one so your two checks are actually assigning values to g
not comparing with g
if (g == 1) {
main();
}
else if (g == 2) {
return 0;
}
Any modern compiler should have given you a compiler warning about that assignment. You should always try to pay attention to compiler warnings.
Also your logic of
if ((n1 || n2) > 10)
and
else if ((n1 || n2) < 0)
is incorrect, but I will leave it to you to figure out what is wrong (this is homework afterall).
Lastly you may want to look in to doing a do-while
loop instead of calling main()
over and over.
答案 1 :(得分:1)
Your if
condition is wrong:
if (g = 1)
sets g
to 1, and is always true. What you want to do is:
if (g == 1)
And as Scott said in his comment, you shouldn't call main but rather use a while
loop.
答案 2 :(得分:0)
请查看这些修改。
float n1;
float n2;
int g = 1;
while (g != 2)
{
cout << "Please enter two grades: " << endl;
cin >> n1;
cin >> n2;
if ((n1 || n2) > 10) {
cout << "Wrong grade";
}
else if ((n1 || n2) < 0) {
cout << "Wrong grade";
}
else {
cout << "The grade average is " << (n1 + n2) / 2 << endl;
cout << "Do you want to insert more grades ? " << endl;
cin >> g;
}
}
return 0;
}
另请注意,我使用main之外的命名空间。