兰德()创造一个奇怪的结果

rand() creating a weird outcome

本文关键字:结果 创造 兰德 一个      更新时间:2023-10-16

编码我的高中课程作业时,我使用了rand(),并意识到它正在创建静态结果。我的代码只是为数组创建9个随机数,然后添加它们。

#include <string>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
  srand( time( NULL ) );
  int array[]={0};
  int i = 0;
  while (i<9){
      array[i]={rand()};
      i++;
  }
  int loop=0;
  int sum=0, num=0;
  while (num<9){
  cout<<"Value "<<num<<": "<<array[num]<<"n";
  sum=sum+array[num];
  num++;
  }
  cout<<"Sum of all values: "<<sum<<"n";
    return 0;
}

使用此代码,有些值似乎是相同的,而另一些值与最后一个相似。
Image1Image2Image3如果您查看值0和3,它们总是有4位数字,而值1总是像0一样始终为2,其余的似乎是随机的。对为什么会发生这种情况有任何想法吗?

您正在从事不确定行为的行为,因为您正在访问其范围之外的数组。

以9号声明它以避免这种情况:

int array[9] = {0};

您的第一个问题是定义 int 数组时,您将其定义为1个元素的值。回复已经从记忆中读取了界限;这些肮脏地址的值未知。

int array[]={0};

定义一个整数数组,其长度为9。我建议使用 #define int const 来定义您的边界。例如,请参见下面

#define MAXINDEX 9
...
    int array[MAXINDEX];
    ...
    while (i < MAXINDEX){
    ...
    while (num < MAXINDEX){
    ...

int const MAXINDEX(9);