C++ 带有 While 运算符的控制台应用程序
C++ console application with While operator
我需要帮助来解决一个问题。我尝试在代码块上运行它,但编译器显示错误(执行"mingw32-g++.exe -c C:\Users\user\Desktop\Test\main.cpp -o C:\Users\user\Desktop\Test\main.o' 在"C:\Windows\system32"中失败),所以我在这里询问一些代码更正(如果需要):
创建一个 C++ 控制台应用程序,该应用程序输入随机数量的值,直到输入 0,并显示所有偶数 [输入] 中最大的一个。
解决方案必须简单,并且没有比if
和while
更复杂的内容。 为了确保您理解,我将举一个例子:您在控制台中输入: 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
将保持未初始化状态,程序将无法正常工作
有几种方法可以解决此问题:
-
手动将
max
初始化为保证小于所有输入数字的值(例如,如果保证所有数字都是正数,则用 -1 初始化max
) -
检查布尔标志以了解何时输入奇数 例如
#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; }
输入第一个偶数, 直到达到奇数,然后用第一个奇数初始化
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
相关文章:
- C++控制台应用程序阻止退出
- 如何在 Win32 C++控制台应用程序中调用 UWP 类库
- 是否可以从控制台应用程序使用 C++/WinRT 创建窗口?
- 如何创建一个使用开源c项目的c++控制台应用程序
- c ++控制台应用程序,如何在控制台外部打印字符
- 将控制台应用程序直接输出到Visual Studio而不是外部Windows控制台中
- 如何在 Win32 控制台应用程序中注册不可见的窗口类?
- 如何将从控制台应用程序C++回调设置为C++ COM DLL
- 使用代码在 AWS 开发工具包C++控制台应用程序上设置凭证
- 直接输入控制台应用程序
- C++调试控制台应用程序
- C++控制台应用程序调用C++/CLI静态库
- 如何在控制台应用程序中添加滚动功能以显示更大的输入
- 如何在将Visual Studio C++控制台应用程序连接到Microsoft SQL Server时修复"
- 如何读取windows服务启动的控制台应用程序的输出
- VS2017 中缺少 Win32 控制台应用程序.如何创建C++空项目?
- 将 Visual C++ 6 控制台应用程序作为 Windows 服务运行
- 如何将控制台应用程序放入系统托盘通知C++?
- 如何向控制台应用程序添加图标
- 如何在 Linux/Apache 虚拟主机上运行 win32 控制台应用程序?