gpt4 book ai didi

c - 将数字分开然后求和的函数

转载 作者:行者123 更新时间:2023-11-30 20:29:43 25 4
gpt4 key购买 nike

我正在尝试解决一个需要我获取号码​​的问题。使用 % 和/取最右边的数字并对分隔的数字求和。然后判断这个数字是否能被 9 整除。

我创建了一个函数来分隔最右边的数字,然后我尝试获取该数字并通过 while 循环运行它。存在的问题是,当我运行 while 循环时。它会创建无限循环,否则将不会打印输出。

#include <stdio.h>

int loopnum(int n);

int main(void)
{
int num;
int sum = 0;
int d = loopnum(num);

printf("Enter a number:\n");
scanf("%d", &num);

while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}

if (num % 9 == 0) {
printf("n = %d is divisible by 9\n", num);
}
else {
printf("n = %d is not divisible by 9\n", num);
}
return 0;
}

int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}
Enter a number:9n = 9 is divisible by 9

这段代码的结果应该是输出 d = "the digital",sum ="digit + sum"且 n = "digit"能被 9 整除。例如,如果我输入 9。输出为 d = 9,sum = 9。

最佳答案

这个函数没有意义。

int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}

例如,对于n等于27,您将得到

n = n % 10;

现在n等于7然后

n = n / 10;

现在n等于0

因此,对于数字 27,函数返回 0

而且在循环内部

while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}

numdsum 均未更改。

定义这样一个函数没有什么意义,除非它本身可以输出中间和和数字。

如果没有该函数,程序可能会如下所示。

#include <stdio.h>

int main(void)
{
while ( 1 )
{
const unsigned int Base = 10;
const unsigned int DIVISOR = 9;

printf( "Enter a non-negative number (0 - exit): " );

unsigned int n;

if ( scanf( "%u", &n ) != 1 || n == 0 ) break;

unsigned int sum = 0;

unsigned int tmp = n;
do
{
unsigned int digit = tmp % Base;
sum += digit;

printf( "d = %u, sum = %u\n", digit, sum );
} while ( tmp /= Base );

printf( "\nn = %u is %sdivisble by %u.\n\n",
n,
sum % DIVISOR == 0 ? "" : "not ", DIVISOR );

}

return 0;
}

它的输出可能看起来像

Enter a non-negative number (0 - exit): 9
d = 9, sum = 9

n = 9 is divisble by 9.

Enter a non-negative number (0 - exit): 123456
d = 6, sum = 6
d = 5, sum = 11
d = 4, sum = 15
d = 3, sum = 18
d = 2, sum = 20
d = 1, sum = 21

n = 123456 is not divisble by 9.

Enter a non-negative number (0 - exit): 0

关于c - 将数字分开然后求和的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56648260/

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