【发布时间】:2014-05-20 17:58:25
【问题描述】:
我必须编写一个程序,要求用户输入一个数字,如果他们输入零,它将打印出他们输入的零,如果他们输入负数或正数,它将打印出他们输入的任何一个一个负数或正数。我有它,所以它不接受字母和逗号等。但我不知道如何让这个不接受小数?任何线索我怎么能做到这一点?除了 cplusplus.com 之外,任何具有良好 c++ 参考的好网站
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
int getInt()
{
int choice=0;
while (!(cin >> choice))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Please input a valid integer: " << '\n';
}
return (choice);
}
int print_zero()
{
cout << "The number you entered is a zero. " << '\n';
return 0;
}
int print_negative()
{
cout << "You entered a negative number. " << '\n';
return 0;
}
int print_positive()
{
cout << "You entered a positive number. " << '\n';
return 0;
}
int main ()
{
cout << "your number please:-" << '\n';
int choice = getInt();
if (choice == 0)
{
print_zero();
}
if (choice < 0)
{
print_negative();
}
if (choice > 0)
{
print_positive();
}
cout << endl << "All done! Nice!!" << endl;
return 0;
}
【问题讨论】:
-
术语说明:在这种情况下,您可能应该使用“浮点”而不是“小数”。 “十进制”在许多库和应用程序中具有特殊含义。
-
您的代码已经拒绝小数点,因为您提取的是整数,而不是浮点变量。
-
@0x499602D2 它将读取该点之前的位并将其转换为 int,但实际上不会出错。
-
'除了 cplusplus.com 之外,任何具有良好 c++ 参考的好网站' 当然:cppreference.com
-
至于你的问题:
cin >> choice不是已经保证只能给出有效的整数吗?还是您想阻止用户输入 s.th。像7.8并且它被接受为有效的int(7)?那么你可以选择 Rook 的答案。
标签: c++ error-checking