gpt4 book ai didi

c++ - 当 "x"不是数字时,如何避免输出零?

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:41 25 4
gpt4 key购买 nike

我正在制作一个数字应用程序,用于判断它是正数、负数、零还是非数字。我只有“不是数字”条件的问题。如果“x”不是数字,如何让计算机显示输入的字符?

#include <std_lib_facilities.h>
using namespace std;
int main()
{
int x;
cout << "x= ";
x;
cin >> x;
if (x > 0)
{
cout << x;
cout << " is a positive number";
}
if (x == 0)
{
cout << x;
cout << " is nil";
}
if (x < 0)
{
cout << "(";
cout << x;
cout << ")";
cout << " is a negative number";
}
if (cin.good())
{
}
else
{
x != 0;
cout << "x";
cout << " is not a number";
}
return 0;
}

出于某种原因,它显示输出为零,而不是我写的那样。

最佳答案

还有一个示例,您将了解如何使用 try-catch 执行此操作。您可以说用户输入的所有内容都是字符串,然后您可以尝试将其解析为 int。但是,用户有可能不会输入字符串,因此您需要尝试解析并捕获发生的任何错误。如果发生错误,则用户输入的不是数字,而是完全不同的东西。如果用户输入了数字,那么你就可以开始了,检查它是正数、负数还是 0。

#include <iostream>

int main(int argc, const char * argv[]) {
std::string x;
std::cout << "Enter a number: " << std::endl;

try {
std::cin>>x;
int number = std::stoi(x);
if (number < 0) {
std::cout << "Negative number" << std::endl;
}
else if (number > 0) {
std::cout << "Positive number" << std::endl;
} else {
std::cout << "You entered number 0" << std::endl;
}
}catch(...) {
std::cout << "Not a number!" << std::endl;
}
return 0;
}

关于c++ - 当 "x"不是数字时,如何避免输出零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com