简体   繁体   English

在C或C ++中执行while循环以获取多个输入

[英]Do while loop in C or C++ for multiple inputs

Following is the code snippet i'm working, although I need 4 values for my input, until the user types correct value, it should keep asking, any inputs on the same Thanks in advance 以下是我正在使用的代码段,尽管我需要输入4个值,但是在用户键入正确的值之前,它应该不断询问,所有输入都相同。

#include<stdio.h>
#include<math.h>

int
main(int argc, char *argv[])
{
        int days;
        float peny;

        do{
                printf("Enter Number of days: ");
                scanf("%d", &days);
        }
        while ((days != 28) || (days != 29) ||(days != 30) ||(days != 31));
        printf("Number of days are %d", days);


}

Think about what your loop condition is saying. 考虑一下您的循环条件在说什么。 It will keep looping whilst any of those individual conditions is still true, or to put it another way, looping until all of them are false simultaneously. 当这些单独条件中的任何一个仍然为真时,它将继续循环,或者换句话说, 一直循环直到所有这些条件同时都为假。 Is that possible? 那可能吗?

while((days<28)||(days>31)); while((days <28)||(days> 31)); // ie. //即 while days are illegal because to low OR too high 几天是非法的,因为过低或过高

The condition 条件

(((days != 28) || (days != 29) ||(days != 30) ||(days != 31)))

in your do-while loop will always be true because the value of days can not be 28, 29,30, 31 at the same time. do-while循环中的值始终为true,因为days的值不能同时为28、29、30、31。 The or operator could be changed to and: 或运算符可以更改为和:

while ((days != 28) && (days != 29) && (days != 30) && (days != 31));

Always test the return status from scanf() ; 始终测试scanf()的返回状态; if it doesn't tell you 1, it is failing, perhaps because the user typed a instead of 31 . 如果没有告诉您1,则失败,可能是因为用户键入a而不是31

Consider counting the number of consecutive failures (and bailing out if the count gets too high) so the user doesn't get frustrated. 考虑对连续失败的次数进行计数(如果计数过多,则进行补救),以使用户不会感到沮丧。

Consider using fgets() to read the input and sscanf() to parse it; 考虑使用fgets()读取输入,并使用sscanf()解析输入; it is generally easier to manage. 通常比较容易管理。

Consider using C++ for C++ and C for C; 考虑将C ++用于C ++,将C用于C。 what you show is a C program rather than a C++ program (though it can indeed be compiled with C++, unless my eyes are deceiving me). 您显示的是C程序而不是C ++程序(尽管确实可以使用C ++进行编译,除非我的眼睛在欺骗我)。 In general, the languages are very different. 通常,语言是非常不同的。

Include a newline at the end of the final printf() . 在最终的printf()末尾添加换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM