[英]A program that checks if the sum of the divisors are equal to the number doesn't work
所以我试着做一个简短的程序,它会得到一个输入 n,它代表你想要输入的数字,然后它检查这个数字的除数之和是否等于它,然后在最后它显示有多少个数的除数之和等于它们,但由于某种原因,它不起作用,它始终显示 0
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n, k, l, i, j, m;
cin >> n;
m = 0;
l = 0;
for (i = 0; i < n; i++){
cin >> k;
m = 0;
for (j = 1; j <= n/2; j++) {
if (k%j == 0) {
m = m + j;
}
}
if (k == m){
l++;
}
}
cout << l;
return 0;
}
使用更有意义的名称会立即暴露错误:
int main()
{
int tests, number, successes, test, candidate, sum;
cin >> tests;
sum = 0;
successes = 0;
for (test = 0; test < tests; test++){
cin >> number;
sum = 0;
for (candidate = 1; candidate <= tests/2; candidate++) {
if (number%candidate == 0) {
sum = sum + candidate;
}
}
if (number == sum){
successes++;
}
}
cout << successes;
return 0;
}
现在很明显,您在最内层循环中使用了错误的上边界。
问题在这里:
for (j = 1; j <= n/2; j++) {
n
告诉您要检查多少个数字,但您实际检查的数字是k
,所以应该是
for (j = 1; j < k; j++) {
假设您想求和所有除数,我还删除了除以 2 的除法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.