所以我的任务就是这个:“使用for循环打印出所有数字(在一行,空格分隔)之间 高度和宽度(包括),然后打印这些数字的平均值(平均值)。“一切正常,直到我到达最底层,我不知道如何在boxWidth和boxHeight之间加上数字并找到它们平均值.boxWidth是我的“x”所以说,boxHeight是我的“y”。
void main() {
int boxHeight = 0;
int boxWidth;
int x;
int numOfItems;
int sumTotal = 0;
double average = 0;
cout << "\tEnter a number from 3 to 10 inclusive: " << endl;
cin >> boxHeight;
//making a calculation for our boxHeight
while (boxHeight < 3 || boxHeight > 10) {
//prompt them to try again if the number they entered isnt within the range we want.
if (boxHeight >= 3 || boxHeight <= 10) {
cout << "That number was not between 3 or 10 inclusive, try again: " << endl;
cin >> boxHeight;
}
}
cout << "The box's height is: " << boxHeight << endl;
//making a calculation for our boxWidth
cout << "Enter a number for your box width that is greater than the height but smaller than 20:" << endl;
cin >> boxWidth;
while (boxWidth < boxHeight || boxWidth > 20) {
//prompt them to try again if the number they entered isnt within the range we want.
cout << "That number doesn't work here, try another: " << endl;
cin >> boxWidth;
}
cout << "The numbers between the box's height and it's width are: " << endl;
for (int i = boxHeight; i <= boxWidth; i++) {
cout << i << " ";
//this is where I'm stuck, can't add up the numbers "i" and then find their average
}
}
答案 0 :(得分:1)
您根本不需要循环来查找平均值
for (int i = boxHeight; i <= boxWidth; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
std::cout << double(boxWidth + boxHeight) / 2;
答案 1 :(得分:0)
您可以添加addidional变量,因此您的循环可能如下所示:
int total = 0;
int size = 0;
for (int i = boxHeight; i <= boxWidth; i++)
{
total += i;
size++;
}
然后打印平均值:
cout<<"average:"<<(float)total/size<<endl;
答案 2 :(得分:0)
加起来并获得平均值
int total = 0, count = 0;
for (int i = boxHeight; i <= boxWidth; i++) {
cout << i << " ";
total = total + i;
count++;
}
cout << endl;
float avg = (float)total / count;
cout << "Average is " << avg << endl;