gpt4 book ai didi

c - 数列中的第 n 个元素,其中数字可被其数字之和整除

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

我应该编写一个程序,从输入中读取正整数 n 并输出该系列的第 n 个元素(可被其数字之和整除的数字。)。该系列的第一个元素是 1,最后一个元素是 10^6(前 20 个元素:1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 12; 18; 20; 21; 24 ;27;30;36;40;42;……)。下面的代码工作正常,但我不应该使用函数。那么如何将函数中的代码放入 for 循环中呢?我遇到了一些问题,但找不到解决方案。

#include <stdio.h>
static int digsum(int n)
{
int sum = 0;
do{
sum += n % 10;
} while (n /= 10);
return sum;
}

int main(void)
{
int n, done, j, temp, temp1,i;
scanf("%d", &temp);
for (i = 1, j = 0; i < 1000; i++) {
if (i % digsum(i) == 0) {
if (j++ <= temp - 1) {
printf("%d ", i);
temp1 = i;
}
}
}
printf("temp1 %d\n", temp1);
return 0;
}

如果我输入 20,我的输出需要是 42。

最佳答案

尝试使用下面的代码

 #include <stdio.h>

int main(void)
{
int n, done, j, temp, temp1,i,sum,k;
scanf("%d", &temp);

for (i = 1, j=0; i<1000; i++) {

/*Implement the function digsum() right away inside main() and create local variables */

k = i; //Taking a copy of i as in the while() condition check the value changes
sum = 0;
do{
sum += k % 10;
}while (k /= 10);
if(i % sum == 0) {
if (j++ <= temp-1) {
printf("%d ", i);
temp1=i;
}
}
}
printf("temp1 %d\n", temp1);
return 0;
}

关于c - 数列中的第 n 个元素,其中数字可被其数字之和整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46237783/

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