【发布时间】:2021-12-21 00:23:42
【问题描述】:
我想将 int 数组转换为字符串并将其反转(问题 2),但我似乎无法使其工作并且不知道如何修复它。我使用sprintf 将我的 int 数组转换为字符串,但它拆分出随机数。
第 2 题是基于第 1 题的,所以这里仍然需要 getsum
“getsum”用于问题 1 和 2
问题的图片如下
问题
(Q.1)An integer n is divisible by 9 if the sum of its digits is divisible by
9.
Develop a program to display each digit, starting with the rightmost digit.
Your program should also determine whether or not the number is divisible by
9. Test it on the following numbers:
n = 154368
n = 621594
n = 123456
Hint: Use the % operator to get each digit; then use / to remove that digit.
So 154368 % 10 gives 8 and 154368 / 10 gives 15436. The next digit extracted
should be 6, then 3 and so on.
(Q.2) Redo programming project 1 by reading each digit of the number to be tested
into a type char variable digit. Display each digit and form the sum of the
numeric values of the digits. Hint: The numeric value of digit is
(int) digit - (int) '0'
代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int reverse(int n) {
char str[100];
sprintf(str, "%d", n);
int d = atoi(_strrev(str)); //str>int//
int arr[100];
int i = 0;
int display = 0;
char digit[100];
while (d != 0) {
display = d % 10;
arr[i] = display;
i++;
d = d / 10;
sprintf(digit, "%d", arr[i]); //int>char!!!//
}
for (i = i - 1; i >= 0; i--) {
printf("%s\n", digit);
}
return 0;
}
int getsum(int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
int main() {
int n;
int i = 0;
printf("input n: ");
scanf("%d", &n);
printf("%d\n", reverse(n));
printf("%d\n", getsum(n));
return 0;
}
我还想澄清一下,在提问方面我是 StackOverflow 的新手,所以如果我做错了什么或没有遵循要求的格式,我很抱歉:D
【问题讨论】:
-
什么是
_strrev? -
strrev()是反转字符串,例如输入:12345 输出:54321 我将输入 int 转换为字符串,而不是使用strrev()来反转转换后的字符串,然后将其转换回 int,这样我就可以用它打印出输入的反转(问题 1),但要求问题 2它被打印为字符串,所以我再次将它从 int 转换为 str 但它不起作用 -
请编辑帖子以显示该代码。我们需要完整的代码为minimal reproducible example。另外,请将任务描述发布为文本而不是图像。
-
printf("%s\n", digit);在for循环中保持不变digit没有意义,因为它只会一遍又一遍地打印相同的值。 -
@chux-ReinstateMonica,我刚刚使图像可见。我不知道您所说的“将文本更改为图像”是什么意思。
标签: arrays c type-conversion reverse