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

C++ console application with While operator

本文关键字:控制台 应用程序 运算符 带有 While C++      更新时间:2023-10-16

我需要帮助来解决一个问题。我尝试在代码块上运行它,但编译器显示错误(执行"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 100

它显示: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;
}

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

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

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

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

  2. 检查布尔标志以了解何时输入奇数 例如

    #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. 输入第一个偶数,
  4. 直到达到奇数,然后用第一个奇数初始化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;
    }
    

你的算法是正确的,你唯一的问题是未初始化的max