抱歉,如果这个问题已在其他地方得到解答,我进行了搜索,但找不到我要找的内容。
无论如何,我遇到了一个大学作业问题,该问题要求我创建一个脚本,随机生成 0-99 之间的数字,并每次在新行上打印该数字,如果刚刚打印的数字落在范围 68-74 然后应该打印 Done!在下一行并退出脚本。
我得到了一个模板,其中大部分代码已经为我完成,它看起来像这样:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
/**
* Your solution must start from below this point. No code modifications WHATSOEVER are allowed ABOVE this point!
*/
/**
* Your solution must have finished by this point. No code modifications WHATSOEVER are allowed BELOW this point!
*/
return 0;
}
int getRandInt() {
return rand() % 100;
}
无论如何,经过一番折腾,我终于让它无限地打印一个随机数列表而不是 1 个随机数。我这样做是使用:
do
printf ("%d\n", getRandInt());
while (getRandInt());
我尝试插入以下内容:
do
printf ("%d\n", getRandInt());
while (getRandInt() <68);
看看它是否至少只打印小于 68 的随机整数,但这只会让它只打印 1 或 2 个随机数(有时值大于 68),而不是前面的代码块打印的巨大列表。
我调用了正确的函数吗?我应该使用 Do While 循环吗?如何设置循环退出并打印“完成!”的数字范围?显然我无法编辑注释之外的代码。
我对编码非常陌生,非常感谢任何有关此问题的帮助。
最佳答案
声明另一个整型变量并在循环内调用该函数。因此每次返回值都会存储在该变量中,使用该变量进行条件检查。
尝试以下代码片段-
/**
* Your solution must start from below this point. No code modifications WHATSOEVER are allowed ABOVE this point!
*/
int ret;
do{
ret = getRandInt();
printf("%d\n",ret);
}while(!(ret >= 68 && ret <= 74));
printf("Done!\n");
/**
* Your solution must have finished by this point. No code modifications WHATSOEVER are allowed BELOW this point!
*/
从上面的代码中,当数字在 68 到 74 之间时,它将打印 Done!
并退出循环。如果不是( !(ret >= 68 && ret <= 74)
),它将继续执行循环,直到数字落在 68 到 74 之间。
关于c - 生成随机数并在 C 中的范围内打印 "Done!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25174305/