0

我对以下算法有疑问,应该怎么做才能解决这个问题 如果年份不是闰年,我将需要再次键入年份,直到键入的年份是闰年。

    int year = 0;        
    BOOL yearC;

    NSLog(@"Enter the year to be tested;");
    scanf ("%i", &year);
    yearC = ((year % 4 == 0 && year % 100 !=0)|| year % 400 == 0);
    if ( yearC  )
             NSLog (@"It's a leap year.");
    else 
    {
        NSLog (@"Nope, it's not a leap year.");
       scanf ("%i", &year);    
    }
}
4

1 回答 1

3

您可以使用while 循环,下面的代码应该适合您:)

只需为 yearC 设置一个起始值,然后重复 while 块,直到 yearC 设置为 YES(是闰年)

BOOL yearC = NO;

while(!yearC){
    NSLog(@"Enter the year to be tested;");
    scanf ("%i", &year);
    yearC = ((year % 4 == 0 && year % 100 !=0)|| year % 400 == 0);
    if ( yearC )
        NSLog (@"It's a leap year.");
    else {
        NSLog (@"Nope, it's not a leap year."); 
    }
}
于 2013-05-24T07:49:05.940 回答