Question

What am i doing wrong? I want to have a random numbers. Negative and positive integers

#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];
}

Im very beginner and I wanted to have random numbers but i have only one very big. Can anybody help?

Sorry, but you see problems which i haven't. Now i know i should only write >>endl

EDIT: I corrected my code and it works now

#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"
}
Était-ce utile?

La solution 2

cin<<a;

Here, you're using the wrong operator. Think of the angle brackets as showing the flow of data. You want:

cin>>a;

Similarly with cout:

cout<<t[i];

You are also indexing t with a, rather than with i, in the first for loop:

t[i]=rand();
//^ This is i, not a

Another problem is that you are using a compiler extension to create an array of run-time size. That is, with standard C++ you cannot use a as the size of your array since it is not known at compile time.

Autres conseils

You haven't seeded the random number generator. Call srand() at the start of your program.

The usual way is to call it with whatever current time is:

std::srand(std::time(0))

You'll need to include <ctime>, too.

Note that rand() doesn't return negative values, that logic you'll need to implement by yourself.

t[i]=rand();

not

t[a]=rand();

or did you write that wrong too?

I'm not sure at 100% but IMO, rand() can create only positive numbers, from 0 to 65535, depending on the time that the executable was compiled: this mean that once you had compiled the .exe file, it will give the same numbers over and over again!

In order to make him produce different numbers you have to use srand().

Another thing: In C++ you can't allocate a dynamic array with type array[n] [it isn't in the standard!], even if the compiler allows you to do it! Actually the compiler translate your code in array = new type[n] that you have to deallocate with the delete[] keyword.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top