【问题标题】:c programming - printing sequence of sum of squared digits (as an array) for a potential happy numberc编程 - 为潜在的快乐数字打印数字平方和的序列(作为数组)
【发布时间】:2015-02-25 04:31:53
【问题描述】:

我的 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 前面多了一个“}”
  • 您可以随时编辑您的问题。

标签: c arrays printing numbers


【解决方案1】:

这一行

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

确保您在一轮后跳出循环,因为a[1] 不等于a[0]。您可以将该行更改为:

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

您还需要添加一个子句以确保在达到数组限制时停止。将该行更新为:

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

然后,将打印循环更改为使用i &lt; count,而不是i &lt;= count。当用户输入一个悲伤的数字时,使用&lt;= 会导致访问数组越界。

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)) );

这将搜索数组中的最后一个数字,但只搜索前一个索引。

【讨论】:

  • 非常感谢,非常有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多