c++ - C++ 数组和元素
问题描述
我的程序专注于这个实验室的数组元素,但我不确定如何将我的平均值设置为请求的特定数字。任何指导都会对这篇文章有所帮助
#include "pch.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int arr[10], n, i, max, min, avg;
cout << "Enter the size of the array: ";
cin >> n;
cout << "Enter the elements of the array: ";
for (i = 0; i < n; i++)
cin >> arr[i];
max = arr[0];
for (i = 0; i < n; i++)
{
if (max < arr[i])
max = arr[i];
}
min = arr[0];
for (i = 0; i < n; i++)
{
if (min > arr[i])
min = arr[i];
}
avg = arr[0];
for (i = 0; i < n; i++)
{
if (avg > arr[i])
avg = arr[i];
}
cout << "Largest element: " << max;
cout << "Smallest element: " << min;
cout << "Average element: " << avg;
}
解决方案
我建议在你的 for 循环中使用 += 运算符,然后除以 n。
float sum = 0;
float avg = 0;
for(i = 0; i < n; i++)
{
sum += arr[i];
}
avg = sum / n;
另外,我建议您使用浮点数或双精度数,而不是使用整数作为平均值,否则您将进行整数除法,这将截断小数。即 5 / 2 = 2
推荐阅读
- python - 使用 Selenium 保存在浏览器中打开的 pdf
- c# - Cariablevalue 更改为我从未分配过的新值
- php - 是否可以在 Laravel 的同一个控制器上同时使用 auth 和 auth:api 中间件?
- html - 游戏的正确 ARIA 属性
- python - 为什么我在 GAN 的训练鉴别器和生成器中得到 nan 损失值?
- docker - 具有 docker 文件支持的 Visual Studio - 没有这样的文件或目录
- cmd - 使用 Windows 批处理列出比另一个文件更新的文件
- pthreads - C p_thread:分段错误
- javascript - Jquery/JS 使用正则表达式检查电子邮件
- javascript - 使用 vue.js 动态向表中添加行