打印“错误”消息C中do-while循环后的语句 [英] Print an "Error" statement after do-while loop in C
本文介绍了打印“错误”消息C中do-while循环后的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在do-while循环后,如何打印一条消息,指出输入错误?还是我使用了错误的循环?
How could I print a message telling the input is wrong after a do-while loop? Or am I using a wrong loop?
#include <stdio.h>
#include <conio.h>
void main(){
int inp;
do{
clrscr();
printf("Enter Number < 10: ");
scanf("%d",&inp);
}
while(inp>10); // Print "Wrong" when inp>10
printf("Right Answer!");
getch();
}
推荐答案
您可以执行以下两项操作之一事情:
You could do one of two things:
在while循环的末尾添加额外的支票:
Add an extra check to the end of your while loop:
if(inp>10){
printf("error");
}
或者您可以避免额外的检查,同时牺牲一些可读性和更改您的while
循环到
or you can avoid the extra check, while sacrificing a bit of readability and change your while loop to
while(inp>10 && printf("error"))
之所以有效,是因为如果第一个语句为true,则 printf()
由于短路而不会执行,但如果为false,则在返回之前将执行 printf()
到循环的顶部。
This works because if the first statement if true, the printf()
will not be executed due to short-circuiting, but if it is false, the printf()
will be executed before the return to the top of the loop.
这篇关于打印“错误”消息C中do-while循环后的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文