c++ - 打印更大数字的程序

标签 c++

$它应该打印 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/

相关文章:

c++ - 为什么mac不需要包含智能指针?

c++ - 如何使用 boost 日志防止内存增长?

c++ - 原始类型的强 typedef (BOOST_STRONG_TYPEDEF 不会削减它)

c++ - 如何在 QRunnable 中休眠?

c++ - 从文件中读取十六进制,printf %x 显示前导 ff 值

c++ - 将 2x32 位大整数除以 1000

c++ - 有没有办法在不覆盖实际分配的情况下使用 vulkan 内部分配回调?

c++ - 传递模板供以后在其他结构/类上下文中使用

c++ - boost 序列化 NVP 宏和非 XML 元素字符

c++ - Qt5:连接:如果插槽的参数少于信号,如何使用 'connect'