Question
Hello I want print numbers from 30 to -30, this is my code
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
srand(time(0));
int arr[20] = {0};
for(int i = 0; i < 20; i++){
arr[i] = rand() % 30+(-30);
}
for(int i = 0; i < 20; i++){
cout << arr[i] << " "<<endl;
}
return 0;
}
I'm not know why, but all numbers are negative ?
Solution
You got a problem in your logic ... You generate numbers from 0-30 and then subtract 30 ... The maximum number you can get is 0...
arr[i] = (rand() % 61) - 30;
gives you what you want
OTHER TIPS
You should have used,
arr[i] = (rand() % 61) - 30
More verbosely,
arr[i] = (-30) + (rand() % ((30)-(-30)+1)) // base + range
Assuming -30 to 30 is an inclusive range.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow