我的程序只输出无零数字...例如输入= 16076,输出= 1676 ...任何人都可以帮助数学
#include <stdio.h>
char *ft_itoa(int n)
{
int count;
int i;
int j = 0;
int temp;
int allocated = 0;
char *val;
int zero;
while (n > 0)
{
count = n;
i = 0;
temp = 1;
while (count > 0)
{
i++;
count /= 10;
printf("works %d\n", i);
}
if (allocated == 0)
{
printf("alocated\n");
allocated = 1;
val = (char *)malloc((i + 1) * sizeof(char));
}
while (i > 1)
{
temp *= 10;
i--;
//printf("temp = %d\n", temp);
}
val[j] = n / (temp) + '0';
n = n - ((temp) * (n / temp));
//val++;
最佳答案
您的代码中有几个问题,与您不模仿通常的atoi无关(它使字符串成为参数,更多的是基数,并且也可用于负数)
您不更改j的值,所以只修改val[0]
,并且因为循环的结尾不可见,所以我们不知道是否将最后一个空字符放在某个位置
您的代码非常复杂,无济于事,例如,为什么要计算位数和每转十的幂?
显然,您不知道模运算符'%'存在
零是没用的
我的程序只输出没有零数字
这是因为您计算每转位数的方式,因此从16076中删除了两位高位数后,您得到076,因此实际上是76,而您绕过了0
计算一次位数后的正确方法是以相反的顺序写数字,从低位开始
例如,如果像我一样分配字符串并且仅管理正数,则解决方案可以是:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Usage: %s <positive number>\n", *argv);
else {
int n;
if ((sscanf(argv[1], "%d", &n) != 1) || (n < 0))
fprintf(stderr, "invalid number '%s'\n", argv[1]);
else {
int v;
size_t ndigits;
if (n == 0)
ndigits = 1;
else
for (v = n, ndigits = 0; v != 0; v /= 10, ++ndigits)
; /* empty body */
char * s = malloc(ndigits + 1);
s[ndigits] = 0;
do {
s[--ndigits] = n % 10 + '0';
n /= 10;
} while (ndigits != 0);
puts(s);
free(s);
}
}
return 0;
}
编译与执行:
pi@raspberrypi:/tmp $ gcc -g -pedantic -Wextra -Wall i.c
pi@raspberrypi:/tmp $ ./a.out 16076
16076
pi@raspberrypi:/tmp $
在valgrind下执行:
pi@raspberrypi:/tmp $ valgrind ./a.out 16076
==6822== Memcheck, a memory error detector
==6822== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6822== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==6822== Command: ./a.out 16076
==6822==
16076
==6822==
==6822== HEAP SUMMARY:
==6822== in use at exit: 0 bytes in 0 blocks
==6822== total heap usage: 2 allocs, 2 frees, 1,030 bytes allocated
==6822==
==6822== All heap blocks were freed -- no leaks are possible
==6822==
==6822== For counts of detected and suppressed errors, rerun with: -v
==6822== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
pi@raspberrypi:/tmp $
关于c - 尝试重建itoa函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56376050/