gpt4 book ai didi

c++ - 我正在尝试在 If 语句中使用数组

转载 作者:行者123 更新时间:2023-11-28 02:43:03 26 4
gpt4 key购买 nike

我试图在 if 语句中使用数组来确定 x 的值是否稀有。

如果我这样做,一切都很正常。

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
int y[5] = {1,2,3,4,5};
srand(time(0));
for(int z = 0; z <= 50; z++){
int x = 1 + (rand()%6);
cout << z;
cout << " " <<x;
if(y[5] == x){
cout << ": Common" << endl;
}else{
cout << ": RARE" << endl;
}
}

但如果我这样做,一切都是罕见的。

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main(){
int y[5] = {1,2,3,4,5};
srand(time(0));
for(int z = 0; z <= 50; z++){
int x = 1 + (rand()%6);
cout << z;
cout << " " <<x;
if(y[5] == ++x){
cout << ": Common" << endl;
}else{
cout << ": RARE" << endl;
}
}

我真的不知道该怎么做,有人能帮帮我吗?

最佳答案

在这两种情况下,您还访问了位置 6(越界)的数组。您很幸运,第一个有效,但第二个无效。

将其更改为 y[4](数组索引从 0 开始)。

关于c++ - 我正在尝试在 If 语句中使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25300214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com