2017-08-12 48 views
-4

每當我嘗試運行程序時,我得到的唯一輸出是來自表達式else,即使條件匹配,if語句也會被忽略。什麼是我的錯誤?` 繼承人關於在c編程中if和else表達式的問題

#include <stdio.h> 
#include <math.h> 
void main() 
{ 
    int a,b,c=0,d,e,f,g,s=0,h,i; 
    printf("Enter the lower limit a\n"); 
    scanf("%d",&a); 
    printf("Enter the upper limit b\n"); 
    scanf("%d",&b); 

    for(e=a;e<=b;e++) 
    { 
     f=e; 
     do{ 
     f=f/10; 
     c++; 
     }while(f!=0); 

     g=e; 
     do{ 
     d=g%10; 
     s=s+pow(d,c); 
     g=g/10; 
     }while(g!=0); 

     if(s==e){ 
      h=s; 
      printf("\nThe number %d is an armstrong number\n",h); 
     } 
     else{ 
      i=e; 
      printf("\nThe number %d is not an armstrong number\n",i); 
     } 
    } 
} 
+0

使用gcc在ubuntu上編譯它 –

+1

您需要在每個循環中重置一些變量。 – BLUEPIXY

+3

當您逐步完成代碼時,調試器會告訴您什麼?如果你還沒有學會使用,現在是完美的時機。作爲一名開發人員,如何使用調試器來追蹤程序的流程並檢查變量的值,沒有更多的寶貴技能。 (你現在也應該學會使用更好的變量名稱和空白空間,閱讀充滿's = s + pow(d,c)'的代碼;'埋在許多其他'a = z; y = r ++中;如果(a == rz * x){}'是非常困難的,那麼我的商店中的代碼會導致編碼人員需要找到新的工作。) –

回答

0

正如BLUEPIXY說,你需要重置每次你的兩個變量的主循環的代碼。另外,正如Ken White所說,你的變量命名選擇幾乎是不可讀的。

這是你有更明智的變量命名的選擇(如果你按照你的算法的細節可以作出更明智的)固定程序:

#include <stdio.h> 
#include <math.h> 
int main() 
{ 
    int lim_low, lim_up, count=0, n_mod, num, n1, n2, n_pow=0, res_1, res_2; 
    printf("Enter the lower limit\n"); 
    scanf("%d",&lim_low); 
    printf("Enter the upper limit\n"); 
    scanf("%d",&lim_up); 

    for(num = lim_low; num <= lim_up; num++) 
    { 
     n1 = num; 
     count = 0; 
     do{ 
      n1 = n1/10; 
      count++; 
     }while(n1!=0); 

     n2 = num; 
     n_pow = 0; 
     do{ 
      n_mod = n2%10; 
      n_pow = n_pow+pow(n_mod,count); 
      n2 = n2/10; 
     }while(n2!=0); 

     if(n_pow == num){ 
      res_1 = n_pow; 
      printf("\nThe number %d is an armstrong number\n", res_1); 
     } 
     else{ 
      res_2 = num; 
      printf("\nThe number %d is not an armstrong number\n",res_2); 
     } 
    } 
    return 0; 
} 

添加註釋到各個階段的代碼也有利於可讀性。最後,據我所知,main()應該返回int而不是void,雖然它不是一個錯誤。您的main()末尾的return 0;也不是必需的,但建議您向操作系統發出信號,指出程序已經正確無誤地終止。