gpt4 book ai didi

c - 二进制数之和

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:46 24 4
gpt4 key购买 nike

我正在使用 Tenenbaum 的 C 和 C++ 复习数据结构,第一章说了一个练习题来对二进制数求和。

我的逻辑:

  1. 二进制转十进制
  2. 求和
  3. 将十进制和转换为二进制

但是,当我通过直接输入方法名称而不是传递可以存储值的变量来传递参数时,问题就出现了。

在调试中,我尝试以十进制和二进制打印总和值。当我一次移动一个时,它给出了正确的结果。

这肯定是一个编译时错误,我的逻辑似乎是正确的。

希望得到一些帮助,因为我需要用C语言解决这个问题。

我使用的编译器是 Mac 上的 gcc。

谢谢

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

long bin2deci(long);
long deci2bin(long);
long add(long, long);

int main(void)
{
long binnum, binnum2;
printf("Enter a number in binary\n");
scanf("%ld", &binnum);
printf("Enter another number in binary\n");
scanf("%ld", &binnum2);
printf("Sum is %ld \n", deci2bin(add(bin2deci(binnum), bin2deci(binnum2))));
return 0;
}

long bin2deci(long a)
{
long digit, decimal, i=0;
while(a != 0)
{
digit = a%10;
a=a/10;
decimal += digit*pow(2, i);
i++;
}
return decimal;
}

long deci2bin(long a)
{
long i = 1, binary =0, rem;
while(a != 0)
{
rem = a%2;
a = a/2;
binary = binary+ (rem*i);
i = i*10;
}
return binary;
}

long add(long a, long b)
{
long sum;
sum = a+b;
return sum;
}

最佳答案

我认为问题在于,因为您忘记初始化decimal

在你这样做之后你会得到正确的输出:

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

long bin2deci(long);
long deci2bin(long);
long add(long, long);

int main(void)
{
long binnum, binnum2;
printf("Enter a number in binary\n");
scanf("%ld", &binnum);
printf("Enter another number in binary\n");
scanf("%ld", &binnum2);
printf("Sum is %ld \n", deci2bin(add(bin2deci(binnum), bin2deci(binnum2))));
return 0;
}

long bin2deci(long a)
{
long digit, decimal = 0;
double i=0;
while(a != 0)
{
digit = a%10;
a=a/10;
decimal += digit * (long int )pow( 2, i);
i++;
}
return decimal;
}

long deci2bin(long a)
{
long i = 1, binary =0, rem;
while(a != 0)
{
rem = a%2;
a = a/2;
binary = binary+ (rem*i);
i = i*10;
}
return binary;
}

long add(long a, long b)
{
long sum;
sum = a+b;
return sum;
}

你可能注意到我将 i 声明为 double 并且当你在这里调用 pow 时我做了一个转换:

decimal += digit * (long int )pow( 2, i);

输出:

==4134== Memcheck, a memory error detector
==4134== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==4134== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==4134== Command: ./program
==4134==
Enter a number in binary
0110
Enter another number in binary
1001
Sum is 1111
==4134==
==4134== HEAP SUMMARY:
==4134== in use at exit: 0 bytes in 0 blocks
==4134== total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==4134==
==4134== All heap blocks were freed -- no leaks are possible
==4134==
==4134== For counts of detected and suppressed errors, rerun with: -v
==4134== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

关于c - 二进制数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46787084/

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