2013-03-05 26 views
-2

的練習要求找到該號碼從1到500,數字具體數字,上升到第三功率的總和等於該特定號碼。糾正我的思維這款C練習

例如1^3 = 1 和371 3^3 + 7^3 + 1^3 = 371

我是如何處理這個問題:

我在想,如果我能有一個有500個插槽的字符串陣列,每個插槽包含一個字符串轉換的數字,然後我可以對每個插槽的字符串進行數學運算。如果他們符合我將適用的標準,那麼該插槽將被打印。

我嘗試了sprintf函數沒有太多成功。在一個循環中,它只是初始化字符串(或者它是數組?在3小時後我感到困惑)[0]插槽,所有其他插槽保持不變。

我不希望你解決演習中,而不是引導我,我的邏輯。如果您想要,請讓我添加我所做的代碼。

+1

如何面對你的想法的最好辦法就是實現它,瞭解它是如何工作的。然後當你遇到一些具體問題時,你可能會回到這裏再問一次。 – LihO 2013-03-05 17:46:10

+0

首先編寫一個以數字作爲輸入參數的函數,並通過分別返回1或0來告訴您數字是否滿足指定的條件。 – sgarizvi 2013-03-05 17:47:34

+0

你寫了一些關於如何解決問題的想法很好,但是這裏的人想看看你實際上已經嘗試過了。 – LihO 2013-03-05 17:47:38

回答

4

總是從明確定義算法開始,讓你知道你在做什麼。將其分解成簡單的步驟。事情是這樣的:

For each integer i in the interval 1 to 500: 
    Check if the condition holds for this i 
    If it holds: 
    Print i 
    else: 
    Do nothing 

現在,您需要:「如果爲了這個,我的條件成立檢查」來定義。我會用一些模數和除法算術來提取數字,但我把細節留給你。

注意,我剛纔講一無所知C或任何其他編程語言。只有當你知道你的算法時,你才應該開始考慮實現。

(有實際上是稍微不同的算法比所述一個以上給出,在這裏有相互嵌套每個數字一個環路的可能性。該解決方案可能是可接受的你,但它不會像通用)

2
for(i=1;i<=500;i++) 
{ 
    //loop for checking each number i 
    int sum=0; // to store the sum of cube of digits 
    int n=i; //copy of i 
    //The below while loops does the task. It extracts a digit from the number and adds its cube to the sum 
    // last digit from the number can be seen by taking its remainder by 10 . For eg 35%10=5 
    //once we have used this digit make the number shorter by dividing by 10. For eg 35/10 becomes 3 (because of integer divisions) 
    while(n>0) 
    { 
     int rem=n%10; //extract the last digit 
     sum+=cube(rem); //cube function raises a number to its cube 
     n/=10; //remove the digit we had extracted earlier from the number 
    } 
    if(sum==i) //we got the number we wanted 
     printf("%d\n",i); 

}