【问题标题】:int returns garbage value [closed]int 返回垃圾值
【发布时间】:2012-11-04 15:35:31
【问题描述】:

我有一个问题:当我的程序执行时,我的 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 translate(pl->en) 中翻译 couts。

【问题讨论】:

  • 请打开编译器的警告。
  • 编译器没有任何警告。
  • 哦。您也需要打开优化才能获得它。 (-O1 -Wall 就足够了。)(并在使用时添加-std=c++0x -pendatic,这样您就知道您正在使用 GCC 扩展。)

标签: c++ netbeans int mingw average


【解决方案1】:

您的程序有一个经典的“减一”错误:在将x 用作a[x] 中的索引之前,您增加了a[x],因此第零个元素保持未初始化:

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

【讨论】:

  • @user1798217 欢迎您!您可能希望通过单击灰色复选标记轮廓来接受答案,以表明您不再寻找改进的答案,并在堆栈溢出时获得全新的徽章。
【解决方案2】:

将变量 suma 初始化为零。

long int suma=0;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多