gpt4 book ai didi

c - 尝试重建 itoa 功能

转载 作者:行者123 更新时间:2023-11-30 20:29:46 28 4
gpt4 key购买 nike

我的程序仅输出非零数字...例如输入= 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(它在参数中获取字符串,更多的基础,并且也适用于负数)这一事实无关 p>

  • 您没有更改j的值,因此您只修改了val[0],并且由于循环的结尾不可见,我们不可见知道您是否将最后一个空字符放在某处

  • 你的代码很复杂,比如为什么每轮都要计算位数和十的幂?

  • 显然你不知道模运算符“%”存在

  • 没用

my program on only outputs none zero numbers

这是因为你计算每轮位数的方式,在你从 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/

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