【发布时间】:2015-11-26 11:45:41
【问题描述】:
所以,我需要在 C 中实现这个公式:
其中 n 由用户输入,并且必须 >= 1。Ci 是数字 n 与 k的第 i 位> 位,而 Ci 与该行是 Ci 的补码(数字 + 补码 = 9)。 例如,数字 21262 满足这个等式,因为:
21262 = 7^5 + 8^4 + 7^3 + 3^2 + 7^1 = 16807 + 4096 + 343 + 9 + 7 = 21262
我尝试过制作算法并将其转换为 C 程序,但是当我执行时,出现了问题。我无法制定执行 k-i+1 幂的循环。
#include <stdio.h>
int main() {
int n, t, k, c, i, s, power, j;
do {
printf("Enter n = ");
scanf("%d", &n);
} while (n < 1);
t = n; // Here we save the value of n, and operate with t
k = 0; // k counts the number of digits
while (t > 0) {
t = t / 10;
k++; // k = number of digits
}
t = n;
s = 0;
for (i = 1; i <= k; i++) { // Starts the sum from i to k
c = 9 - t % 10; // Complements the digits
power = 1;
for (j = 1; j <= k-i+1; j++) // Start of loop that powers th number
power = c * power;
s = s + power;
t = t / 10;
}
if (s == n)
printf("The number fulfills the equation");
else
printf("The number doesn't fulfill the equation");
return 0;
}
如您所见,我尝试通过将 c 补码乘以自身 k-i+1 次的循环来解决功率问题。但有些不对劲。请帮忙!
【问题讨论】:
-
你从左到右而不是从右到左阅读数字
-
为了我们人类的可读性,请始终缩进代码。通常,在每个左大括号 '{' 之后缩进,在每个右大括号 '}' 之前不缩进