gpt4 book ai didi

c++ - 在预测错误的用户输入的情况下获取数字的平均值

转载 作者:行者123 更新时间:2023-12-02 10:29:17 25 4
gpt4 key购买 nike

#include <iostream>
#include <string>

using namespace std;

int main(void) {

float sum, counter = 0, num;
string d;
bool t = true;

while (t) {
cin >> num;
sum = sum + num;

counter += 1;

while (cin.fail())
{
cin.clear();
cin.ignore();
cin >> d;

if (d == "done") {
t = false;
continue;
} else {
cout << "Invalid" << endl;
continue;
}
}
}
cout << sum << ' ' << counter << ' ' << (sum / counter);
return 0;
}

**因此,我尝试使用输入猜测来计算输入数字的平均值,如下所示:
4 5 BadInput 7
-----
Expected output should be:
Enter a number: 4
Enter a number: 5
Enter a number: bad data
Invalid
Enter a number: 7
Enter a number: done
16 3 5.333333333333333
我的代码有什么问题?

最佳答案

如果要处理错误的输入,建议将输入读入字符串,然后进一步处理该字符串。这将使循环本身更加简单:

std::string d;
float sum = 0;
int counter = 0;

while (std::cin >> d) {
if (d == "done") {
break;
}

try {
sum += std::stof(d);
counter++;
} except (std::logic_error &e) {
std::cerr << "Invalid input\n";
}
}

std::cout << sum << ' ' << counter << ' ' << (sum / counter) << '\n';

关于c++ - 在预测错误的用户输入的情况下获取数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62960784/

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