简单的c++程序,有点迷失,需要指导
Simple C++ Program, kind of lost and need guidance
我现在正在做一项作业,我有点不知道怎么做。
这是关于分配的信息:
计算一组数字的最大值、最小值、计数、平均值和标准差(std dev)。
平均值公式为:平均值是总和除以计数
标准差公式为:Stddev是方差的平方根
方差公式为:方差是(平方和除以计数)减去平均值的平方。
关于平方和,我的意思是对于像:2 3 4这样的列表,平方和是4 9 16,因此平方和是29。
当提示"输入另一个?"输入n以离开提示并计算输出值。键入y或任何其他单个字符以继续输入值。
下面是解决方案的截图/示例运行:https://i.stack.imgur.com/ncHof.png
这是我到目前为止写的
#include <iostream>
using namespace std;
double k;
char another;
int main()
{
cout <<"nEnter a number:";
cin >> k;
cout <<"nEnter another?";
cin >> another;
if(another=="y")
double max,min,sum,average,standard,variance,count;
sum = k +
average = sum / count;
variance =
cout <<"nMax Value:"<< max;
cout <<"nMin Value:"<< min;
cout <<"nCount:" << count;
cout <<"nAverage:" << average;
cout <<"nStd Dev:"<< variance;
return 0;
}`
我如何使它,如果用户输入Y,他可以输入另一个数字像分配说给?n离开提示符,计算
我该如何使它显示最低和最高的值为min/max?
如何获得为计数输入的值的数量?
谢谢你们了!
我如何使它,如果用户输入Y,他可以输入另一个数字,就像分配说的?n表示离开提示符并计算
您可以将程序放入while循环中,如果用户输入n
,它将跳出循环。
bool inputting_Numbers = true;
while (inputting_Numbers) {
// get data
cin >> another;
if (another == 'n')
inputting_Numbers = false;
}
// calculations
或者,为了使它更好,而不是询问用户是否想要输入另一个数字,让它只在某个字符上中断,例如s
表示停止或b
表示中断。
bool inputting_Numbers = true;
while (inputting_Numbers) {
// get data
cin >> another;
if (another == 'b' || another == 's')
inputting_Numbers = false;
}
//calculations
还必须将数字放入数组或向量中。如果你有一组数字,一个变量是不够的。既然你正在使用c++,我建议你使用vector
我该如何让它显示最小/最大的最小和最大值?
您可以创建一个函数来查找数组或向量的最小和最大数字。那就把它打印出来。
如何获得为计数输入的值的数量?
如果你使用的是矢量,你可以直接使用
vectorName.size();
来获取数字的数量。如果使用数组,可以通过
获取数字的数量。int amount = sizeof(arrayName) / sizeof(int);
您需要一个while循环来单独处理每个数字,然后在用户完成后处理总数。你的算法是:
- 设置sum和things为0 开始你的while循环
- 得到输入
- add to sum and sum_of_squares
- 增加数
- 检查max和min是否
- 请求继续和停止while循环,如果用户不
- 计算平均值和std_dev
- 打印所有的
代码:
#include <iostream>
#include <limits>
#include <cmath>
int main()
{
float sum = 0;
float sum_of_squares = 0;
int count = 0;
// Initialize max and min to things they can't possibly be
float max = std::numeric_limits<float>::min();
float min = std::numeric_limits<float>::max();
float num;
bool done = false;
char should_continue = 'y';
while(should_continue != 'n')
{
std::cout << "Enter a number : ";
std::cin >> num;
//update sum and sum_of_squares and count
//check if we've found a bigger or smaller number
//if the number is bigger than max or smaller than min, update them
std::cout << "Enter another? : ";
std::cin >> should_continue;
//if should_continue == n, the loop exits
}
//use our shiny info to get what we really want
//Use your formulas and the sqrt() function from cmath to get answers
std::cout << "Max : " << max << std::endl;
std::cout << "Min: " << min << std::endl;
std::cout << "Count: " << count << std::endl;
std::cout << "Average: " << avg << std::endl;
std::cout << "Std. Dev.: " << std_dev << std::endl;
}