尝试重建 ITOA 函数

  • 本文关键字:函数 ITOA 重建 c
  • 更新时间 :
  • 英文 :


我的程序只输出零数字...例如输入 = 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 %dn", i);
}
if (allocated == 0)
{
printf("alocatedn");
allocated = 1;
val = (char *)malloc((i + 1) * sizeof(char));
}
while (i > 1)
{
temp *= 10;
i--;
//printf("temp = %dn", 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 $ 

瓦尔格林德的处决:

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 $ 

最新更新