【发布时间】:2016-04-11 14:15:08
【问题描述】:
我的 C 课程大约有 4 周的时间,并且正在开发一个基本上会输出以下内容的程序 -
./perfect
Enter number: 6
The factors of 6 are:
1
2
3
6
Sum of factors = 12
6 is a perfect number
./perfect
Enter number: 1001
The factors of 1001 are:
1
7
11
13
77
91
143
1001
Sum of factors = 1344
1001 is not a perfect number
到目前为止我的工作 -
// Testing if a number is perfect
#include <stdio.h>
int main (void) {
//Define Variables
int input, sum;
int n;
//Obtain input
printf("Enter number: ");
scanf("%d", &input);
//Print factors
printf("The factors of %d are:\n", input);
n = 1;
while (n <= input) {
if (input % n == 0) {
printf("%d\n", n);
}
n = n + 1;
}
//Sum of factors
//printf("Sum of factors = %d", sum);
//Is it a perfect number?
if (sum - input == input) {
printf("%d is a perfect number", input);
} else if (sum - input == !input) {
printf("%d is not a perfect number", input);
}
return 0;
}
所以我已经完成了第一部分和最后一部分(我认为)。这只是总结了我正在努力解决的因素。
如何将所有因素加在一起?它应该是第一个 while 循环的一部分,还是单独放置?
任何帮助将不胜感激!
谢谢!
【问题讨论】:
-
你的意思是
if (sum - input == input) {是if ((sum - input) == input) {? -
if (sum - input == input) {应该是if (sum == input) {并且else子句不需要任何if。
标签: c while-loop sum logic