编写一个程序,将整数转换成字符串:void itoa(int, char);C语言代码。并在main函数中调用。
时间: 2023-06-06 19:05:20 浏览: 51
以下是C语言代码:
#include <stdio.h>
#include <stdlib.h>
void itoa(int num, char str[]) {
int i = 0;
while (num > 0) {
str[i++] = (num % 10) + '0';
num = num / 10;
}
str[i] = '\0';
int len = i;
for (i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = temp;
}
}
int main() {
int num = 12345;
char str[20];
itoa(num, str);
printf("The string representation of %d is %s\n", num, str);
return 0;
}
相关问题
编写一个程序,将整数转换成字符串:void itoa(int, char)。C语言代码。
下面是C语言代码:
```
void itoa(int num, char str[])
{
int i = 0;
while (num != 0) {
str[i++] = num % 10 + '0';
num /= 10;
}
str[i] = '\0';
// reverse the string
int j = i - 1;
i = 0;
while (i < j) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
++i;
--j;
}
}
```
这个函数可以将一个整数转换为字符串。它接受一个整数和一个字符数组作为参数,将转换后的字符串存储在字符数组中。
编写一个程序,将整数转换成字符串:void itoa(int, char);C语言
中没有内置的 itoa() 函数,需要自己编写实现。以下是示例代码:
void itoa(int n, char s[]) {
int i, sign;
if ((sign = n) < 0) // 记录符号
n = -n; // 把 n 变为正数
i = 0;
do {
s[i++] = n % 10 + '0'; // 取下一个数字
} while ((n /= 10) > 0); // 删除该数字
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s); // 反转字符串
}
其中 reverse() 函数可以按照以下实现:
void reverse(char s[]) {
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) { // i 从头开始,j 从尾部开始,两两交换字符
c = s[i];
s[i] = s[j];
s[j] = c;
}
}