if数组上的随机数

Random numbers on if array

本文关键字:随机数 数组 if      更新时间:2023-10-16

我正试图在一个包含年龄数字的数组中找到最高的项。问题是它会在if行返回随机数。我想弄清楚背后的逻辑。

语言是C++,我确信这很容易解决。

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int edad[100], n, i, emayor=0;
float suma;

do {
cout << "Ingrese su edad: ";
cin >> edad[i];
suma+=edad[i];
i++;
cout << "nnDesea Ingresar Edades? (1/0) ";
cin >> n;
} while(n==1 && i<100);
cout << "La sumatoria de edades es: "<< suma;

if (edad[i]>emayor) {
emayor=edad[i];
cout << "nLa edad mayor es: "<<emayor;
}
getch();
return 0;
}

您的程序有未定义的行为,因为您使用的是isuma而没有初始化它们。

此外,在使用数字之前,请确保检查数字提取是否成功。

使用

int edad[100] = {}; // Initialize the elements to zero.
int n = 0;          // It's a good practice to initialize all variables.
int i = 0;
int emayor = 0;
float suma = 0;
do{
cout << "Ingrese su edad: ";
if ( ! (cin >> edad[i]) )
{
// Error in reading from cin.
// Add error handling code, or break out of the loop.
break;
}
suma += edad[i];
i++;
cout << "nnDesea Ingresar Edades? (1/0) ";
cin >> n;
} while ( n == 1 && i < 100 );
...