當我運行這個 C 程式并給出 2020、2024 或其他年份完全可以被 4 整除時,我得到了預期的輸出,即這是閏年。 但是當我給出一個世紀年:1900、2000 或 2100 等作為輸入時,它并沒有給我任何輸出。
請不要向我推薦正確的程式,因為互聯網上有很多可用的程式,我已經理解了。請您告訴我為什么我的程式在進入世紀時沒有任何輸出。
PS這個程式沒有錯誤。
程式:
#include <stdio.h>
int main()
{
int n;
printf("Enter year : "); scanf("%d",&n);
if (n%4==0)
{
if(n%100 != 0)
{
printf("Leap year");
}
}
else if(n%100 == 0)
{
if (n%400==0)
{
//`enter code here`
printf("Leap year");
}
}
else
printf("Not a Leap year");
return 0;
}
uj5u.com熱心網友回復:
這部分代碼有問題:
if (n%4==0)
{
if(n%100 != 0)
{
printf("Leap year");
}
}
當你輸入 1900 時,它進入第一個條件。(因為 1900%4 等于 0。)然后,它檢查 19000 是否為零,如您所見,它為零,所以它沒有進入 if(n0!=0 ) 條件,并且 if (n%4==0) 中沒有其他 else 陳述句。所以沒有條件讓代碼進入。因此它沒有給出任何輸出。另外,您的代碼永遠不會進入else if(n0 == 0)部分,因為任何能被 100 整除的數字也能被 4 整除。
uj5u.com熱心網友回復:
這個 if 陳述句
if (n%4==0)
{
if(n%100 != 0)
{
printf("Leap year");
}
}
獲得像 1900 年這樣的年份的控制權,因為它們可以被 4 整除。但是由于這樣的年份也可以被 100 整除,因此不會輸出任何內容。
所以你的程式有一個邏輯錯誤。
例如,您可以通過以下方式重寫 if 陳述句
if ( ( n % 4 != 0 ) || ( n % 100 == 0 && n % 400 != 0 ) )
{
printf("Not a Leap year");
}
else
{
printf("Leap year");
}
或者
if ( ( n % 4 == 0 ) && ( n % 400 == 0 || n % 100 != 0 ) )
{
printf("Leap year");
}
else
{
printf("Not a Leap year");
}
或者如果使用嵌套的 if-else 陳述句,那么代碼看起來像
if ( n % 4 == 0 )
{
if ( n % 400 == 0 )
{
printf("Leap year");
}
else if ( n % 100 != 0 )
{
printf("Leap year");
}
else
{
printf("Not a Leap year");
}
}
else
{
printf("Not a Leap year");
}
uj5u.com熱心網友回復:
您的邏輯具有以下結構:
if ( n % 4 == 0 )
{
if ( n % 100 != 0 )
{
printf( "Leap year\n" );
}
}
else if ( n % 100 == 0 )
{
if ( n % 400 == 0 )
{
printf( "Leap year\n" );
}
}
else
{
printf( "Not a Leap year\n" );
}
我不會寫 ,而是在每個陳述句中else if添加大括號,以清楚地表明實際指的是什么。添加大括號不會改變程式的行為。{ }elseelse
if ( n % 4 == 0 )
{
if ( n % 100 != 0 )
{
printf( "Leap year\n" );
}
}
else
{
if ( n % 100 == 0 )
{
if ( n % 400 == 0 )
{
printf( "Leap year\n" );
}
}
else
{
printf( "Not a Leap year\n" );
}
}
現在可以清楚地看到,如果if條件n % 4 == 0為真,則執行第一個外部塊,否則執行第二個外部塊。
然而,這個邏輯是錯誤的。如果條件n % 4 == 0為真,則將執行第一個外部塊,這意味著"Leap year"如果if條件為真,您的程式將列印,但如果條件為假n % 100 != 0,則不執行任何操作(即不列印) 。if這不是你想要的。
您想要的是以下邏輯:
if ( n % 4 != 0 )
{
printf( "Not a Leap year\n" );
}
else
{
if ( n % 100 != 0 )
{
printf( "Leap year\n" );
}
else
{
if ( n % 400 != 0 )
{
printf( "Not a Leap year\n" );
}
else
{
printf( "Leap year\n" );
}
}
}
這可以通過洗掉所有大括號來更緊湊地撰寫:
if ( n % 4 != 0 )
printf( "Not a Leap year\n" );
else if ( n % 100 != 0 )
printf( "Leap year\n" );
else if ( n % 400 != 0 )
printf( "Not a Leap year\n" );
else
printf( "Leap year\n" );
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470610.html
