int返回垃圾价值
int returns garbage value
我有一个问题:执行程序时,我的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;
相关文章:
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- 如何正确重载 << 运算符以返回 int 值?
- 返回 int 时的分段错误
- 返回int数据类型v/s传递参考
- char*中存储的返回int值(0-255)给出了负值
- C++. 面试. 关于返回 int* 值问题的范围
- 调用从Java返回INT值的C 函数
- 使用 static int 返回 int&in 函数
- 从函数 CPP 返回 int 或 string.c_str() 时的两个不同的行为
- 超能力 NDK 安卓:返回 int 在"extern"块中成功,在调用函数中失败
- 如何使用 boost::bind 将返回 int 的函数转换为返回布尔值的函数
- 为什么在应该返回对象的方法中返回 int 是有效的
- main() 总是返回 int
- 从函数返回"int * const"
- C++函数向字符串变量返回int
- 从返回int的函数中获取char的正确方法
- 为什么这个阶乘函数返回int而不是double
- 为什么 isnan、isinf 和 isfinite 返回 int 而不是布尔值
- 返回 std::string 的函数在没有 return 语句的情况下崩溃,这与返回 int 而不返回语句的函数不同