gpt4 book ai didi

c++ - 如何正确实现一个循环,询问用户是否要重新执行代码?

转载 作者:行者123 更新时间:2023-11-28 04:19:31 24 4
gpt4 key购买 nike

在我的一个 C++ 类作业中,我被赋予了任务:

编写一个程序,读取 float 列表,然后打印出值的计数、平均值和标准差。

您可以假设用户的输入始终有效,并且该列表至少包含两个数字。

您可以假设列表中的数字由一个空格字符分隔,并且列表中最后一个数字后面的字符是换行符。

实现一个循环,在该循环中重复上述操作,直到用户请求退出。

我正在努力完成最后一步,我需要询问用户是否要继续。我的代码如下。


#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>

using namespace std;
int main()
{

char counter;



do {
char ch = ' ';

int i = 0;

double sum = 0;

double average = 0;

double sum_squared = 0;

cout << "Please enter a list of values (of type double): ";

do {

double x;

cin >> x;

ch = cin.get();

i += 1;

sum += x;

double x_squared = pow(x, 2);

sum_squared += x_squared;

} while (ch != '\n');

average = sum / i;

double standard_deviation = sqrt((sum_squared - (pow(sum, 2) / i)) / (i - 1));

cout << "Number = " << i << endl;

cout << "Average = " << average << endl;

cout << "Standard deviation = " << standard_deviation << endl;

cout << "Continue? (y,n) "; cin >> counter;



} while (counter = 'y');
return 0;
}

我原以为当用户最后输入 y 时,程序会重新执行。但结果很奇怪。当我输入 n 时,代码仍然重新执行。谁能解释为什么?此外,如何在我的代码中正确实现此功能?感谢大家的帮助和回复。

最佳答案

改变

counter = 'y'

counter == 'y'

接近尾声将产生令人满意的结果。

关于c++ - 如何正确实现一个循环,询问用户是否要重新执行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786708/

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