我想將 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;
}
問題 2
我還想澄清一下,我在提問方面是 StackOverflow 的新手,所以如果我做錯了什么或沒有遵循所需的格式,我很抱歉:D
uj5u.com熱心網友回復:
如果我是對的,每次呼叫該行時都會sprintf(digit, "%d", arr[i])覆寫緩沖區digit,因此,最終您會得到錯誤的答案。您可以使用第一個的回傳值,sprintf()即已寫入的符號數和任務的提示。我們得到
// Code
int ndigits = sprintf(str, "%d", n);
// Code
char number[100];
number[ndigits--] = '\0';
while (d != 0) {
display = d % 10;
i ; // Now there's no need for this line. The number of digits is already
// counted
d = d / 10;
number[ndigits] = display '0'; // Use the hint
}
UPD:您也可以使用malloc()版本
char *number = malloc(ndigits 1); // Add one for the null terminator
// Same code
free(number); // Free in the end
uj5u.com熱心網友回復:
您不需要反轉字串。此外,int要將char數字轉換為數字,您只需要執行char_digit = int_digit '0'.
同樣在您的代碼中,for回圈中存在一個錯誤,您應該使用不同的變數進行回圈(如j)。
int reverse(int n) {
int d = n, i = 0;
char digit[100] = {0}; // will initialize digit with zeros
while (d != 0) {
digit[i] = (d % 10) '0'; // '0' 1 = '1', '0' 4 = '4'
d = d / 10;
i ;
}
for (int j = i - 1; j >= 0; j--) {
printf("%c", digit[j]);
}
printf("\n");
return 0;
}
如果你想列印n相反的數字,即如果n是 2345 而你想列印 5432,那么只需更改for回圈:
for (int j = 0; j < i; j ) {
printf("%c", digit[j]);
}
printf("\n");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352610.html
上一篇:如何創建如下所述的陣列?
下一篇: a與C 陣列中的 1不同?
