有关循环问题
#include <stdio.h>int main()
{
int year,month,day;
int ret;
printf("请输入一个日期:(格式:yyyy-mm-dd)");
while((ret=scanf("%d-%d-%d",&year,&month,&day))!=EOF)//想让其能重复查询,这样用while却行不通
{
if(ret!=3)
printf("请输入正确的格式!");
if(month<1 || month>12)
printf("月份输入错误!");
if(year<0)
printf("年份输入错误!");
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: if(day<1 || day>31){
printf("该月份最多31天");
return 0;
}
switch(month){
case 4:
case 6:
case 9:
case 11:if(day>30) {
printf("该月份最多30天!");
return 0;}
case 2:if((year%100!= 0 && year%4== 0)|| year%400== 0)
{if(day>29) printf("闰年二月最多29天!"); return 0;}
else {
if(day>28) printf("非闰年二月最多28天!"); return 0;}
}
}
//泰勒公式
int w,c,y,m,d;
if(month== 1 || month== 2){
y= year-1;
m= month+12; }
else
{
y= year;
m= month;
}
c= y/100;
y= y%100;
d= day;
w =(y+ (int)y/4+ (int) c/4-2*c+ (int) (26*(m+1)/10)+d-1)%7;
switch(w){
case 0:printf("%4d-%02d-%02d为星期天\n",year,month,day);break;
case 1:printf("%4d-%02d-%02d为星期一\n",year,month,day);break;
case 2:printf("%4d-%02d-%02d为星期二\n",year,month,day);break;
case 3:printf("%4d-%02d-%02d为星期三\n",year,month,day);break;
case 4:printf("%4d-%02d-%02d为星期四\n",year,month,day);break;
case 5:printf("%4d-%02d-%02d为星期五\n",year,month,day);break;
case 6:printf("%4d-%02d-%02d为星期六\n",year,month,day);break;
default: printf("Error-%d",w);
}
return 0;
}
}
问题如下:
如何用while使用户能重复查询?
#include <stdio.h>
int main()
{
int year=-1,month=-1,day=-1;
int ret;
char exit=0;
while(1)//想让其能重复查询,这样用while却行不通
{
printf("请输入一个日期:(格式:yyyy-mm-dd)\n");
ret=scanf("%d-%d-%d",&year,&month,&day);
if(ret!=3)
{
while((exit=getchar())!='\n'){if('Q'==exit||'q'==exit)break;};
if('Q'==exit||'q'==exit)break;
printf("请输入正确的格式!\n");
continue;
}
if(month<1 || month>12)
printf("月份输入错误!");
if(year<0)
printf("年份输入错误!");
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: if(day<1 || day>31){
printf("该月份最多31天");
return 0;
}
switch(month){
case 4:
case 6:
case 9:
case 11:if(day>30) {
printf("该月份最多30天!");
return 0;}
case 2:if((year%100!= 0 && year%4== 0)|| year%400== 0)
{if(day>29) printf("闰年二月最多29天!"); return 0;}
else {
if(day>28) printf("非闰年二月最多28天!"); return 0;}
}
}
//泰勒公式
int w,c,y,m,d;
if(month== 1 || month== 2){
y= year-1;
m= month+12; }
else
{
y= year;
m= month;
}
c= y/100;
y= y%100;
d= day;
w =(y+ (int)y/4+ (int) c/4-2*c+ (int) (26*(m+1)/10)+d-1)%7;
switch(w){
case 0:printf("%4d-%02d-%02d为星期天\n",year,month,day);break;
case 1:printf("%4d-%02d-%02d为星期一\n",year,month,day);break;
case 2:printf("%4d-%02d-%02d为星期二\n",year,month,day);break;
case 3:printf("%4d-%02d-%02d为星期三\n",year,month,day);break;
case 4:printf("%4d-%02d-%02d为星期四\n",year,month,day);break;
case 5:printf("%4d-%02d-%02d为星期五\n",year,month,day);break;
case 6:printf("%4d-%02d-%02d为星期六\n",year,month,day);break;
default: printf("Error-%d",w);
}
}
return 0;
} jhq999 发表于 2021-10-31 11:53
那如何退出呢? waixiong 发表于 2021-10-31 18:12
那如何退出呢?
退出的话在73行之后写一段类似于这样的代码就好了
int ch;
printf("是否继续查询:(Y/N)");
ch = getchar();
if(ch == 'N')
{
break;
}
页:
[1]