int返回垃圾价值

int returns garbage value

本文关键字:返回 int      更新时间:2023-10-16

我有一个问题:执行程序时,我的int返回的价值太大。该程序计算算术平均值。

例如:当我键入1,2,3,4,5时,它说 2293393

/* 
 * File:   main.cpp
 * Author: Natch
 *
 * Created on 4 listopad 2012, 15:32
 */
#include <cstdlib>
#include <iostream>
using namespace std;
/*
 * 
 */
int main(int argc, char** argv) {
    int n,x;
    x = 0;
    /*
     * a - array
     * x - repeat
     * n - array fields
     * suma - array fields sum
     */
    cout << "Srednia liczb" << endl;
    cout << "Program oblicza srednia z x liczb." << endl;
    cout << "Podaj ilosc liczb do obliczenia sredniej:" << endl;
    cin >> n;
    int a[n];
    while(x<n) {
        x++;
        cout << "Podaj " << x << " liczbe:" << endl;
        cin >> a[x];
    }
    long int suma;
    for (int i = 0; i < n; i++) {
        suma += a[i];
    }
    int srednia = suma/n;
    cout << "Srednia wynosi:" << endl << srednia << endl;
    system("pause");
    return 0;
}

对不起,我的英语,我来自波兰。

您可以在Google翻译中翻译COUTS(pl-> en)。

您的程序在一个"错误"中具有经典的" OFF:您在使用a[x]中的索引之前递增x,因此Zeroth元素保持不可传统化:

while(x<n) {
    cout << "Podaj " << (x+1) << " liczbe:" << endl;
    cin >> a[x++];
}

初始化变量suma为零。

long int suma=0;

而不是在cout之前增加x,而是在cout中递增。

cout << "Podaj " << x++ << " liczbe:" << endl;