$
它应该打印 5 个数字中所有大于 80 的数字。
但是我写的程序只打印第一个大于 80 的数字。
我怎样才能打印出所有大于 80 的数字?
这是我的代码..
int main ()
{
int num1,num2,num3,num4,num5;
cout << "Enter five marks : ";
cin >> num1 >> num2 >> num3 >> num4 >> num5;
cout << endl;
cout << "Marks are greater than 80 is : ";
{
if (num1 > 80)
cout << num1 << endl;
else if(num2 > 80)
cout << num2 << endl;
else if(num3 > 80)
cout << num3 << endl;
else if(num4 > 80)
cout << num4 << endl;
else if(num5 > 80)
cout << num5 << endl;
else
cout << "error" << endl;
}
最佳答案
删除那些 else
根据您的条件。
if (num1 > 80)
cout << num1 << endl;
if(num2 > 80)
cout << num2 << endl;
if(num3 > 80)
cout << num3 << endl;
if(num4 > 80)
cout << num4 << endl;
if(num5 > 80)
cout << num5 << endl;
你也可以使用循环,因为你在做同样的事情:
int num[5];
cout << "Enter five marks : ";
for (int i=0; i<5; i++)
cin >> num[i];
cout << "Marks are greater than 80 is : ";
for (int i=0; i<5; i++)
if (num[i]>80)
cout << num[i] << endl;
我无法理解你的最后else cout << "error" << endl;
.也许您想警告用户至少输入一个大于八十的数字?然后你可以试试这个:
bool flag = false;
for (int i=0; i<5; i++)
if (num[i]>80)
{
cout << num[i] << endl;
flag = true;
}
if (flag)
cout << "Error" << endl;
关于c++ - 打印更大数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19639034/