带有While运算符的C ++控制台应用程序

时间:2017-05-14 13:46:25

标签: c++

我需要帮助解决我需要解决的问题。我试图在代码块上运行它,但编译器显示错误(执行' mingw32-g ++。exe -c C:\ Users \ user \ Desktop \ Test \ main.cpp -o C :\ Users \ user \ Desktop \ Test \ main.o'在C:\ Windows \ system32'失败),所以我在这里询问一些代码更正(如果需要)代替:

  

创建一个c ++控制台应用程序,输入一个随机数值,直到输入0,并显示[输入]中所有不均匀数字中最大的一个。

解决方案必须简单,并且不得包含比ifwhile更复杂的解决方案。 只是为了确保你明白我会举个例子: 您进入控制台: 2 7 9 4 6 10 0

显示: 9 这是程序应该如何工作的一个示例,而不是它在现实中如何与我的代码一起使用! 以下是我现在尝试做的事情:

#include <iostream>

using namespace std;

int main()
{
    int a, max;
    cout<<"insert number here:";
    cin>>a; //Inserting first "a" so that I can save max a value of first a and compare it to the next entered values
    if (a%2!=0)max=a;
    while(a!=0)
    {
        cin>>a;
        if(a%2!=0 && a>max)max=a;
    }
    cout<<max;
    return 0;
}

**注意:**我更感兴趣的是找到解决此问题的方法,而不是修复代码块错误,但如果能为这两个问题提供帮助,我将很高兴!

1 个答案:

答案 0 :(得分:1)

如果您输入的第一个号码是偶数,max将保持未初始化状态且程序无法正常工作

有几种方法可以解决这个问题:

  1. 手动将max初始化为保证小于所有输入数字的值(例如,如果保证所有数字都是正数,则用-1初始化max

  2. 检查bool标志以了解奇数被输入的时间 e.g。

    #include<iostream>
    using namespace std;
    int main()
    {
        bool foundodd = true;
        int max = 0;
        int a = 0;
        while (cin >> a && a != 0)
        {
            if (a % 2)
            {
                if (foundodd)
                {
                    if (a > max)
                    {
                        max = a;
                    }
                }
                else
                {
                    max = a;
                    foundodd = true;
                }
            }
        }
        cout << max;
    }
    
  3. 输入第一个偶数,直到达到奇数,然后用第一个奇数初始化max

    #include<iostream>
    using namespace std;
    int main()
     {
        int a = 0, max = 0;
        while (cin >> a && a % 2 == 0)
        {
    
        }
        max = a;
        while (a != 0)
        {
            cin >> a;
            if (a % 2 && a > max)
            {
                max = a;
            }
        }  
       cout<<max;
       return 0;
    }
    
  4. 您的算法是正确的,您唯一的问题是未初始化的max