[英]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.