正数和负数
Numbers positive and negative
我做错了什么?我想要a
随机数。负整数和正整数
#include <iostream>
#include <cstdlib>
int main(){
int a;
cin<<a;
int t[a];
for(int i=0;i<a;i+=1)
t[a]=rand();
for(int i=0;i<a;i++)
cout>>t[i];
}
我是个初学者,我想用随机数,但我只有一个很大的。有人能帮忙吗?
对不起,你看到了我没有看到的问题。现在我知道我应该只写>>endl
编辑:我纠正了我的代码,它现在工作
#include <cstdlib>
#include <time.h>
int main(){
int a;
cin>>a;
for(int i=0;i<a;i++)
cout<<(rand()-rand())<<endl;//i asked only for this "endl"
}
您还没有为随机数生成器设定种子。在课程开始时致电srand()
。
通常的方法是用当前时间来称呼它:
std::srand(std::time(0))
您还需要包括<ctime>
。
请注意,rand()
不会返回负值,您需要自己实现该逻辑。
cin<<a;
这里,您使用了错误的运算符。可以将尖括号想象成显示数据流。您想要:
cin>>a;
类似于cout
:
cout<<t[i];
在第一个for
循环中,您还使用a
而不是i
为t
编制索引:
t[i]=rand();
//^ This is i, not a
另一个问题是,您正在使用编译器扩展来创建运行时大小的数组。也就是说,对于标准C++,您不能使用a
作为数组的大小,因为它在编译时是未知的。
t[i]=rand();
不是
t[a]=rand();
还是你也写错了?
我不确定是100%,但IMO,rand()
只能创建正数,从0
到65535
,这取决于编译可执行文件的时间:这意味着一旦编译了.exe
文件,它就会一遍又一遍地给出相同的数字!
为了让他产生不同的数字,你必须使用srand()
。
另一件事:在C++中,您不能用type array[n]
分配动态数组[它不在标准中!],即使编译器允许您这样做!实际上,编译器在array = new type[n]
中翻译您的代码,您必须使用delete[]
关键字来处理这些代码。
相关文章:
- 没有找到相关文章