簡體   English   中英

c編程-潛在幸福數字的平方和之和(作為數組)的打印序列

[英]c programming - printing sequence of sum of squared digits (as an array) for a potential happy number

我在C編程類入門中有這份作業,我的代碼的一部分必須找到一個數字的平方數之和的順序,以便確定給定的數字是否為快樂數之后(平方數的總和= 1 )

這是我的代碼的一部分:

#include <stdio.h>
#include <math.h>

//平方和功能

int sqd (int x) {

int sum = 0;

while (x > 0) {

    sum = sum + pow(x%10, 2);
    x = x/10;
}
return sum;
}

//搜索功能

int search (int a[], int val, int size) {

    int i;

    for (i = 0; i < size; i++) {
        if (a[i] == val) {
            return 1;
        }
    }

   return 0;
}

//主程序

void main () {

    int a [1000] = {0};
    int N;
    int count = 1;
    int j;

    printf("Please enter the potential happy number:\n", N);

    scanf ("%d", &N);

    a[0] = N;
    a[count] = sqd (N); 

    do {    
        a[count] = sqd (a[count-1]);
        count++;
    } while (search (a, a[count], count));

    for ( j = 0; j <= count; j++) {  
        printf("%d\n", a[j]);
    }
}

它僅打印序列中的前三個和。 我真的不知道如何使它工作。

先感謝您

這條線

while (search (a, a[count], count));

確保由於a[1]不等於a[0]在一輪之后退出循環。 您可以將該行更改為:

while (a[count-1] != 1);

您還需要添加一個子句以確保在達到數組限制時停止。 將該行更新為:

while (a[count-1] != 1 && count < 1000 );

然后,更改打印循環以使用i < count而不是i <= count 當用戶輸入一個悲傷的數字時,使用<=將導致對數組的訪問超出范圍。

for ( j = 0; j < count; j++){  

   printf("%d\n", a[j]);
}

更新

在Wikipedia上閱讀了一些快樂的數字后,我了解了您為什么要在while條件下進行search 以下內容也適用。

} while ( ! (a[count-1] == 1 || search(a, a[count-1], count-1)) );

這將搜索數組中的最后一個數字,但僅搜索前一個索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM