我正在制作ac程序,后来必须在raspberry pi上运行,程序从命令行获取一个参数,确定它的值是否介于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");
}
}
Run Code Online (Sandbox Code Playgroud)
当我编译这个在线在这里,有$./a.out 1,我得到以下错误:
数量是:1
分段故障
输入:
./a.out 12
Run Code Online (Sandbox Code Playgroud)
预期产量:
the number is:12
Correct inputBinary is: 1100
Run Code Online (Sandbox Code Playgroud)
我在stackoverflow上找到的转换方法.
***编辑我的新答案:
#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");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
the number is:3
Correct input
Rec call
Rec call
Base c
Binary is: 11
Run Code Online (Sandbox Code Playgroud)
如何二进制必须为0011 3.这部分是我现在正在做的工作.
你在这里有错误的格式说明符:
printf("Binary is: %s \n", convert(v));
Run Code Online (Sandbox Code Playgroud)
convert返回int但%s需要一个char*.
你需要:
printf("Binary is: %d \n", convert(v));
// ^----
Run Code Online (Sandbox Code Playgroud)
传递给该计划的第一个论点是argv[1],而不是argv[2]
因此:
printf("the number is:%s \n", argv[1]);
// ^----
Run Code Online (Sandbox Code Playgroud)
和
int v = atoi(argv[1]);
// ^----
Run Code Online (Sandbox Code Playgroud)