我正在尝试计算并显示c ++中5个数字的平均值,我正在挑战自己不要使用:全局变量,标签或go-to语句,无限循环和break语句来退出循环。我被卡住了,任何人都可以帮我解决这个问题:我需要提示用户结束5个数字,然后计算并显示5个数字的平均值。谢谢。
这是我尝试过的代码:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
// create a variable x.
int x;
// create a variable called average to get the 5 numbers
// calculation.
int average;
// Prompt the user to enter five numbers.
cout << "Please enter five numbers." << endl;
cout << average << endl;
// Calculate the five numbers.
average = x;
cout << "The average for the five numbers are:" << average << endl;
return 0;
}
答案 0 :(得分:3)
使用数组的解决方案。
frame(S) = struct('cdata',[],'colormap',[]); % pre-allocate frames structure
for i = 1 : round(N/S) : N
some plotting code..
axis equal
drawnow;
frame(i) = getframe();
end
答案 1 :(得分:1)
您可以使用以下代码,我使用的变量与您使用的变量非常相似(这只是一个代码段):
int x;
int sum=0;
cout << "Please enter five numbers." << endl;
for(int i=0; i<5; i++){
cin>>x;
sum += x;
}
cout << sum/5.0 << endl;
修改强>
如果您根本不想使用循环,那么您可以使用称为递归的技术来执行此操作:
// Example program
#include <iostream>
#include <string>
int calc(int sum, int i){
if(i == 0){
return sum;
}else{
int x;
std::cin>>x;
i--;
sum+=x + calc(sum, i);
}
return sum;
}
int main()
{
int i=5;
int sum=0;
sum = calc(sum, i);
std::cout<<std::endl<<sum/5.0;
return 0;
}
我希望这很有帮助。
答案 2 :(得分:1)
我已经解决了我自己的问题。正如我所说,我正在避免global variables, labels or go-to statements, infinite loops, and break statements to exit loops
。所以,这是我的答案:
这是我的代码:
#include <iostream>
using namespace std;
int main() {
// Creating variables.
float v, w, x, y, z, average;
// Prompting the user to enter first number.
cout << "Please enter first number: ";
// Getting the input from the user.
cin >> v;
// Prompting the user to enter second number.
cout << "Please enter second number ";
// Getting the input from the users.
cin >> w;
// Prompting the user to enter third number.
cout << "Please enter third number ";
// Getting the input from the user.
cin >> x;
// Prompting the user to enter fourth number.
cout << "Please enter fourth number ";
// Getting the input from the user.
cin >> y;
// Prompting the user to enter fifth number.
cout << "Please enter fifth number ";
// Getting the input from the user.
cin >> z;
// Calculating the average of those user input five numbers.
average = (v + w + x + y + z) / 5;
// Displaying the total average of the five numbers entered.
cout << "The average of the five numbers is:" << average << endl;
return 0;
}
答案 3 :(得分:-1)
这里有一些应该有用的代码:
#include <iostream>
#include <stdio.h>
using namespace std;
int main(int argc, char** argv) {
int main(int argc, char** argv) {
float x = 0;
int i;
int a;
int size;
cout << "How many numbers? ";
cin>> size;
for (i = 1; i <= size; i++) {
cout << "Please enter number #" << i << ": ";
cin >>a;
x += a;
}
cout << "The average for the five numbers are: " << x/(float)size << endl;
return 0;
}
当程序询问有多少个数字时,你可以输入5(它只是让你找到一些数值的平均值)。希望这有帮助!