首页 > 解决方案 > 如何在 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;
}

标签: c++

解决方案


使用数组的解决方案。

#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;
}

推荐阅读