【发布时间】:2019-09-25 08:56:32
【问题描述】:
我必须用 C 语言编写一个程序,它接受整数、sumOfDig 和 lengthOfNum。 sumOfDig 等于数字的总和,lengthOfNum 等于数字的长度。 我不允许使用数组或 math.lib
1 ≤ sumOfDig ≤ 81 和 1 ≤ lengthOfNum ≤ 9
我试图编写一个while循环,但我想不出一种方法可以构建一个数字并从数字之和中减去最后添加的数字。
#include <stdio.h>
#include <stdlib.h>
int main() {
int lengthOfNum; /* stores the length of the number */
int sumOfDig; /* stores the sum of the digits */
int ans; /* stores the answer */
scanf("%d", &sumOfDig); /* scans the sum of the digits */
scanf("%d", &lengthOfNum); /* scans the length of the number */
ans=0; /* initializes ans */
/* adds a number to ans, and removes it from sumOfDig */
while(sumOfDig!=0 && lengthOfNum!=0) {
/*???*/
lengthOfNum--;
};
printf("%d\n", ans); /* prints the outcome */
return 0;
}
以下应该是输入和输出:
输入:20 2 输出:不可能
In: 20 3 Out: 992(因为长度是3和9+9+2=20)
In: 50 8 Out: 99999500(因为长度是8和9+9+9+9+9+5+0+0=50)
【问题讨论】:
-
什么意思,不允许使用数组?你能具体说明一下吗?
-
我不允许在我的代码中以任何方式使用数组。例如:不允许将每个数字都存储在数组中。
-
如果您想使用 scanf %d 解决方案,那么您可以使用基于 %10 和 /10 的循环。如果您不想坚持这一点,那么对字符串表示形式的流式解析器一次消耗一个字符可能会更简单。