【问题标题】:Random numbers on if arrayif数组上的随机数
【发布时间】:2020-07-09 17:41:42
【问题描述】:

我正在尝试在包含年龄数字的数组中找到最高的项目。 问题是它会在 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 << "\n\nDesea 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;
}

【问题讨论】:

  • i 在那一行上有什么值?

标签: c++ random numbers


【解决方案1】:

您的程序具有未定义的行为,因为您使用 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 << "\n\nDesea Ingresar Edades? (1/0) ";
 cin >> n;
} while ( n == 1 && i < 100 );

...

【讨论】:

  • 谢谢。事实上,if 语句应该在 for 循环中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多