[英]How to fill a 2D array with a result from division of 2 random numbers in 2 different ranges but the result being in certain range?
I need to fill a 2D array with result from division of 2 random numbers in 2 different ranges but the result can't be in range (-2,2).我需要用 2 个不同范围内的 2 个随机数相除的结果填充一个二维数组,但结果不能在范围 (-2,2) 内。 Ranges of two random numbers are (-15,5) and (-2,2).
两个随机数的范围是(-15,5)和(-2,2)。 When I Compile & Run the program it it does not work properly.
当我编译并运行该程序时,它无法正常工作。 It outputs just a few lines or nothing and finishes itself.
它只输出几行或什么都不输出,然后自行完成。 I am using Dev-C++.
我正在使用 Dev-C++。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
int array[11][11];
int num1 = 0;
int num2 = 0;
int res = 0;
srand(time(NULL));
for (int i = 0;i < 11;i++) {
for (int j = 0;j < 11;j++) {
do {
num1 = (rand() % (5 + 15 + 1)) - 15;
num2 = (rand() % (2 + 2 + 1)) - 2;
res = num1 / num2;
printf("%d/%d=%d\t", num1, num2, res);
} while (res >= -2 && res <= 2);
array[i][j] = res;
printf("\narray[%d][%d]=%d",i,j, array[i][j]);
printf("\n");
}
}
}
Ouput:输出:
-15/-1=15
array[0][0]=15
-2/2=-1 5/-2=-2 1/1=1 -13/1=-13
array[0][1]=-13
-6/-2=3
array[0][2]=3
-12/1=-12
array[0][3]=-12
--------------------------------
Process exited after 4.478 seconds with return value 3221225620
Press any key to continue . . .
You are almost there.你快到了。 You need to avoid dividing with 0 .
您需要避免除以 0 。 Let's change your
do
- while
to the following:让我们将您的
do
- while
更改为以下内容:
do {
num1 = (rand() % (5 + 15 + 1)) - 15;
num2 = (rand() % (2 + 2 + 1)) - 2;
res = (num2 != 0) ? (num1 / num2) : 0; //we default to 0 if the division was with 0
printf("%d/%d=%d\t", num1, num2, res);
} while (res >= -2 && res <= 2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.