use*_*767 0 c if-statement while-loop conditional-statements
是否有更好的方法通过消除ifC语句中的重复条件来编写以下代码?
while (n < 0) {
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Error: please enter a positive integer\n");
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
当给出正确的输入时,只需重新设计循环中断.这样检查只进行一次:
while (1)
{
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n >= 0)
break;
printf("Error: please enter a positive integer\n");
}
Run Code Online (Sandbox Code Playgroud)
并且,如注释中所指定的,优化的编译器应该能够自行反转循环.