gpt4 book ai didi

c - 用 C 语言进行二进制到十进制转换器

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

我是用 C 语言编写的新手,我不太明白为什么这个程序会导致失败。我觉得这是 isTrue 方法的结果。该方法的目的是确保输入的字符串是一个实际的整数,但它似乎在那里不起作用。我不太确定为什么。由于某种原因,我收到一些奇怪的值。

/* Program: binToDec.c
Author: Sayan Chatterjee
Date created:1/25/17
Description:
The goal of the programme is to convert each command-line string
that represents the binary number into its decimal equivalent
using the binary expansion method.
*/

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

/*Methods*/
int strLen(char *str);
int isTrue(char *str);
int signedBinToDec(char *str);

/*Main Method*/
int main(int argc, char **argv)
{
/*Declaration of Variables*/
int binNum = 0;
int decNum = 0;
int i;

/*Introduction to the Programme*/
printf("Welcome to Binary Converter\n");
printf("Now converting binary numbers\n");
printf("...\n");

/*Check to see any parameters*/
if(argc > 1)
{
for(i = 1; i < argc; i++)
{
if(isTrue(argv[i] == 1))
{
if(strLen(argv[i] <= 8))
{
binNum = atoi(argv[i]);
decNum = signedBinToDec(binNum);
}
else
{
printf("You did not enter a 8-bit binary\n\a");
break;
}
break;
}
else
{
printf("You did not enter a proper binary number\n\a");
break;
}
}

/*Printing of the Result*/
printf("Conversion as follows: \n");
printf("%d\n", decNum);

}
else
{
printf("You did not enter any parameters. \a\n");
}
}

int strLen(char *str)
{
int len = 0;
while(str[len] != '\0')
{
len++;
}
return len;
}

int isTrue(char *str)
{
int index = 0;
if(str >= '0' && str <= '9')
{
return 1;
}
else
{
return 0;
}
}


int signedBinToDec(char *str)
{
int i;
int len = strLen(str);
int powOf2 = 1;
int sum = 0;

for(i = len-1; i >= 0; i--)
{
if(i == 0)
{
powOf2 = powOf2 * -1;
}
sum = (str[i]*powOf2) + sum;
powOf2 = powOf2 * 2;
}
return sum;
}

最佳答案

if声明

  if( isTrue(argv[i] == 1) )

这是非常错误的。不好是因为两种情况

  • argv[i] == 1是指针和 int 之间的比较,这是非法的。这会导致违反约束。根据C11 ,第 §6.5.9 章,相等运算符

    One of the following shall hold:

    — both operands have arithmetic type;

    — both operands are pointers to qualified or unqualified versions of compatible types;

    — one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or

    — one operand is a pointer and the other is a null pointer constant.

  • 比较的结果还是 int值,被用作函数参数,而该函数应该接受 char * 。安intchar *不是兼容的类型。

看来你是想写

  if ( isTrue(argv[i]) == 1 )

因为您需要比较 isTrue 的返回值打电话。

strLen(argv[i] <= 8) 也是如此以及其他。

<小时/>

也就是说,还有其他问题。

  • isTrue()仅检查索引 0 中的值,对于传递的参数,您需要某种循环来检查整个字符串

  • 已经有众所周知的库函数,例如 isDigit() 它的工作效果非常好,请尝试使用它们。

关于c - 用 C 语言进行二进制到十进制转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496189/

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