这是我的功能
int nepresnost_N2(int S){
int N2, N2_1, N2_2;
N2_1 = -S/10;
N2_2 = S/10;
N2 = rand() % (N2_2 + 1 - N2_1) + N2_1;
printf("%i", N2);
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何为(没有0)创造条件.任何想法,谢谢:)
由于你的射程既有消极和积极的一面,从去-s到+s,可以缩短1范围的积极作用,那么万一加1时,产生的值是无负:
N2_1 = -S/10;
N2_2 = S/10-1; // Shrink by one
N2 = rand() % (N2_2 + 1 - N2_1) + N2_1;
if (N2 >= 0) { // Correct for zero
N2++;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将结果检查为零,并在必要时生成新数字:
int nepresnostNoZero(int S) {
int res;
do {
res = nepresnost_N2(S);
} while (res == 0);
return res;
}
Run Code Online (Sandbox Code Playgroud)