gpt4 book ai didi

c - 随机填充 vector 始终返回相同的数字

转载 作者:行者123 更新时间:2023-11-30 18:46:32 24 4
gpt4 key购买 nike

我对 C 完全陌生,尝试用随机整数填充 vector ,然后输出它。然而, vector 似乎总是填充相同的数字。我需要改变什么才能真正获得随机付款?没有限制,数量只能在long的取值范围内。这是我的代码:

    #include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <time.h>

int main()
{
long x = 20;
long y = 12;
std::vector<long> entries;

//initialize simple random number generator using current time
srand(time(NULL));

for (int step = 0; step < x; step++) {
entries.push_back(rand());
++entries[step];
}

for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
printf("%ld\n", i);
}

return 0;
}

编辑:我想使用纯 C 而不是 c++ 来解决问题!

最佳答案

代码中的主要问题是在最后一个循环中

for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
printf("%ld\n", i);
}

您不是打印 vector 中的值,而是打印指向它的迭代器

将循环内的行更改为 printf("%ld\n", *i); 来修复它。

更好的是,您可以使用范围循环使其变得更加简单

for(auto& number : entries){
std::cout<<number<<'\n'; //or printf("%ld\n",number), like in your code
}

关于c - 随机填充 vector 始终返回相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50841015/

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