c++ - 如何在 C++ 中计算并显示 5 个数字的平均值?
问题描述
我试图在 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;
}
解决方案
使用数组的解决方案。
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
int n, i;
vector<double> nums;
double sum = 0.0, average;
cout<<"Enter the numbers of elements: ";
cin>>n;
for(i = 0; i < n; ++i)
{
cout<<"Enter number: "<<i+1;
cin>>num[i];
sum += num[i];
}
average = sum / n;
cout<<"Average = "<<average
return 0;
}
推荐阅读
- python - 如何在 discord.py 中使字符串长于 1 个单词?
- algorithm - 使用“Low-Down Triple Dealing”魔术技巧来确定牌在牌组中的位置的算法是什么
- mysql - 将 MySQL 十进制数转换为千克单位
- javascript - 检查对象数组中的元素
- c# - 在尝试添加迁移时,我收到以下错误,我的数据库尚未创建,所以我不知道如何启用它
- sql-server - 以自定义 JSON 格式返回结果
- java - 为什么在哈希映射中存储哈希映射时填充多个哈希映射而不是 1?
- r - DT 表也下载隐藏列
- python - 每月汇总值后创建新数据框
- java - Linux:驱动程序在目标文件夹中不可执行