2012-11-04 149 views
1

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

例如:当我输入1,2,3,4,5时,它说。

/* 
* 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翻译(pl-> en)中翻译couts。

+3

请打开您的编译器的警告。 – Mat

+1

编译器没有任何警告。 – sofalse

+1

哦。您还需要启用优化才能获得它。 ('-O1 -Wall'就足够了。)(并且在你使用的时候加上'-std = C++ 0x -pendatic',这样你就知道你使用的是GCC扩展。) – Mat

回答

4

你的程序有一个经典的“关闭的一个”错误:你使用它作为a[x]指数前增加x,所以零个元素仍然未初始化:

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

'suma' is未初始化。 – Mat

+0

非常感谢,现在可以使用。 – sofalse

+1

@ user1798217不客气!您可能希望通过点击灰色复选标记大纲来接受答案,以表明您不再寻找改进的答案,并在堆栈溢出时获得全新的徽章。 – dasblinkenlight

2

初始化变量SUMA为零。

long int suma=0; 

相反cout之前递增x的,增加它在cout

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