gpt4 book ai didi

C 整数转二进制

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:35 25 4
gpt4 key购买 nike

我正在制作一个 c 程序,稍后必须在树莓派上运行,该程序从命令行获取一个参数,确定其值是否在 0 到 15 之间。如果是,则将其转换为二进制并返回。

如果没有,则打印一条错误消息。

这是代码:

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

int convert(int dec)
{
if (dec == 0)
{
return 0;
}
else
{
return (dec % 2 + 10 * convert(dec / 2));
}
}

int main(int argc, char *argv[])
{
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments

printf("the number is:%s \n", argv[2]);

int v = atoi(argv[2]);
int bin = 0;

if(v >= 0 && v <= 15){
printf("Correct input");
bin = convert(v);
printf("Binary is: %s \n", convert(v));
}
else{
printf("Inorrect input, number cant be accepted");
}
}

当我在线编译时here ,使用 $./a.out 1,我得到以下错误:

the number is:1
Segmentation fault

输入:

./a.out 12

预期输出:

the number is:12
Correct inputBinary is: 1100

我在stackoverflow上找到的convert方法。

***编辑我的新答案:

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

int convert(int dec)
{
if (dec == 0)
{
printf("Base c\n");
return 0;
}
else
{
printf("Rec call\n");
return ((dec % 2) + 10 * convert(dec / 2));
}
}

int main(int argc, char *argv[])
{
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments

int v = atoi(argv[2]);
printf("the number is:%d \n", v);


int bin = 0;

if(v >= 0 && v <= 15){
printf("Correct input \n");
bin = convert(v);
printf("Binary is: %d \n", bin);
}
else{
printf("Inorrect input, number cant be accepted");
}
}

输出:

the number is:3                                                                                                                    
Correct input
Rec call
Rec call
Base c
Binary is: 11

3 的二进制必须是 0011。这部分是我现在正在做的。

最佳答案

你在这里有错误的格式说明符:

printf("Binary is: %s \n", convert(v));

convert 返回一个 int%s 需要一个 char*

你需要:

printf("Binary is: %d \n", convert(v));
// ^----

传递给程序的第一个参数是argv[1],而不是argv[2]

因此:

printf("the number is:%s \n", argv[1]);
// ^----

int v = atoi(argv[1]);
// ^----

关于C 整数转二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49534008/

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