gpt4 book ai didi

c++ - IF 或 WHILE 用于数字输入检查器

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:27 33 4
gpt4 key购买 nike

我一直在开发一个程序来计算用户输入的平均值。我还不知道输入检查器要用什么。我还不能使用数组或字符串。如何检查两个输入是否都是数值?如果他们不是;如何再次询问正确的输入?

#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value

// Compute and print the mean of the user input

int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}

最佳答案

您可以使用 cin.fail检查错误。请注意,如果用户输入数字后跟字母,可以说 123abc , 然后 x将存储为 123但是abc保留在输入缓冲区中。您可能希望立即清除它 abc不会出现在下一个循环中。

while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;

bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');

if (error)
{
cout << "Input incorrect" << endl;
continue;
}

accumulator = accumulator + x;
number = number + 1;
}

或者你可以初始化x .例如

double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');

if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}

如果发生错误则x保持不变并且您知道出现错误,因为用户输入的数字不太可能与 numeric_limits<double>::min() 匹配

与此问题无关,但您还应该考虑被零除的错误。

if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;

关于c++ - IF 或 WHILE 用于数字输入检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39718074/

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