gpt4 book ai didi

c - 在 C 中实现求和公式

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:31:36 25 4
gpt4 key购买 nike

所以,我需要在 C 中实现这个公式:

enter image description here

其中 n 由用户输入,必须 >= 1。Cink 的第 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 次的循环来解决幂问题。但是有些不对劲。请帮忙!

最佳答案

当您从右到左阅读时,幂应该是 i 而不是 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 <= i; 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 - 在 C 中实现求和公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com