gpt4 book ai didi

c - 将负整数转换为字符串时如何处理?

转载 作者:行者123 更新时间:2023-11-30 18:11:06 24 4
gpt4 key购买 nike

我需要将整数转换为字符串,无论是负数还是正数。到目前为止,我可以使用以下代码将正整数转换为字符串。但不是消极的。我如何正确处理它们以将它们转换为字符串。这是我正在使用的代码。

谢谢

拉贾特!

 /*
* C Program which Converts an Integer to String & vice-versa
*/

#include <stdio.h>
#include <string.h>
#include <math.h>

void tostring(char [], int);


int main()
{
char str[10];
int num, result;

printf("Enter a number: ");
scanf("%d", &num);
tostring(str, num);
printf("Number converted to string: %s\n", str);


return 0;
}

void tostring(char str[], int num)
{
int i, rem, len = 0, n;

if(num<0)
{
n=(-1)*(num);

}
else
{
n=num;
}
while (n != 0)
{
len++;
n /= 10;
}
for (i = 0; i < len; i++)
{
rem = num % 10;
num = num / 10;
str[len - (i + 1)] = rem + '0';
}
str[len] = '\0';
}

最佳答案

在执行其他操作之前,请查看 n 是否为负数。如果是,则以符号 - 开始输出(确保 len 也比其他情况下多 1,并且字符串化在一个字符后开始), n 积极,并像之前一样继续。

关于c - 将负整数转换为字符串时如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51872086/

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