兰德()创造一个奇怪的结果
rand() creating a weird outcome
编码我的高中课程作业时,我使用了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);
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 如何解决这个超硬恒星的创造问题
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 算术运算的结果类似于:C浮点变量中的1/3
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 密码登录程序将永远循环并显示不正确的结果
- 如何让C++'tally up'结果并制定计划?
- 兰德()创造一个奇怪的结果