我是C的新手,我无法弄清楚如何在控制台中传递此错误时摆脱此错误。我试着看其他问题,但实际上我不知道该寻找什么。我试着看看argv的通行证,但没有找到任何突出的东西。
./calculate factorial 4
Segmentation fault (core dumped)
程序:
#include "calculate.h"
int main(int argc, char * argv[])
{
if(strcmp(argv[1], "factorial") == 0){
int result = factorial(argc, argv);
printf("%d\n", result);
}
else if(strcmp(argv[1], "combination") == 0){
int result = combination(argc, argv);
printf("%d\n", result);
}
else if(strcmp(argv[1], "permutation") == 0){
int result = permutation(argc, argv);
printf("%d\n", result);
}
else if(strcmp(argv[1], "pythagorean") == 0){
int result = pythagorean(argc, argv);
printf("%d\n", result);
}
else{
printf("You did not use a valid input!\n");
}
printf("Assignment1-4");
return 0;
}
int factorial(int argc, char * argv[]){
int i = atoi(argv[3]);
if ( i == 0 ){
return 1;
}
return(i * factorial((i - 1),argv));
}
int combination(int argc, char * argv[]){
int n = atoi(argv[3]);
int i = atoi(argv[4]);
return(factorial(n,argv) / (factorial(i,argv) * factorial((n- i), argv)));
}
int permutation(int argc, char * argv[]){
int n = atoi(argv[3]);
int i = atoi(argv[4]);
return(factorial(n,argv) / factorial((n-i), argv));
}
int pythagorean(int argc, char * argv[]){
int c = 0;
int a = atoi(argv[3]);
int b = atoi(argv[4]);
c = (a*a) + (b*b);
c = sqrt(c);
return c;
}
我只是找不到问题,谢谢。
答案 0 :(得分:1)
在函数factorial()中,将argv [3]赋值给i。但是,当您使用./calculate factorial 4
运行程序时,您没有argv [3]条目。这意味着argc只有3(argv数组的长度是3)。您正在访问其范围之外的argv []数组。使用i = atoi(argv[2])
获取预期值。
同样在递归调用中,i总是用argv []值初始化。所以它永远不会达到0并导致无限循环。
如下所示写factorial()并从main()调用factorial(atoi(argv[2]))
int factorial(int i){
if ( i == 0 ){
return 1;
}
return(i * factorial((i - 1));
}
答案 1 :(得分:-1)
你为参数3和4屈服,但你永远不会提供这些参数。所以有例外。 在这里你应该如何实施该程序
这里是
的命令./calculate factorial 4
./calculate combination 4 3
./calculate permutation 6 3
./calculate pythagorean 3 4
这是源
#include <stdio.h>
#include <math.h>
int main(int argc, char* argv[])
{
if(strcmp(argv[1], "factorial") == 0){
int result = factorial(atoi(argv[2]));
printf("%d\n", result);
}
else if(strcmp(argv[1], "combination") == 0){
int result = combination(atoi(argv[2]), atoi(argv[3]));
printf("%d\n", result);
}
else if(strcmp(argv[1], "permutation") == 0){
int result = permutation(atoi(argv[2]), atoi(argv[3]));
printf("%d\n", result);
}
else if(strcmp(argv[1], "pythagorean") == 0){
int result = pythagorean(atoi(argv[2]), atoi(argv[3]));
printf("%d\n", result);
}
else{
printf("You did not use a valid input!\n");
}
printf("Assignment1-4");
return 0;
}
int factorial(int i){
if ( i == 0 ){
return 1;
}
return(i * factorial(i-1));
}
int combination(int n, int i){
return(factorial(n) / (factorial(i) * factorial((n- i))));
}
int permutation(int n, int i){
return(factorial(n) / factorial(n-i));
}
int pythagorean(int a, int b){
int c = 0;
c = (a*a) + (b*b);
c = sqrt(c);
return c;
}