2015-02-10 33 views
-1

我就試圖在KARATSUBA MULTIPLICATION上編寫一個程序,但只要輸入第二個數字,它就會顯示分段錯誤(核心轉儲)錯誤。只要我輸入

我還沒有在程序中包含所有的情況(只有兩個數字具有相等數字的情況)。我非常新,所以無法使用GDB來解決問題。

#include<stdio.h> 
#include <math.h> 
int pro(int,int); 
int digits(int); 
int main() 
{ 
    int s,q,r; 
    printf("enter the two no."); 
    scanf("%d",&s); 
    scanf("%d",&q); 
    r=pro(s,q); 
    printf("the product is %d",r); 
    return 0; 
} 
int pro(int x,int y) 
{ 
    int dig,a,b,c,d,p1,p2,p3,p; 
    dig=digits(x); 
    if(dig>1){ 
    b=x%((int)pow(10,(d/2))); 
    a=x/pow(10,(d/2)); 
    d=y%((int)pow(10,(d/2))); 
    c=y/pow(10,(d/2)); 
    p1=pro(a,c); 
    p2=pro(b,d); 
    p3=pro(a+b,c+d); 
    p=(pow(10,dig)*p1)+(pow(10,dig/2)*(p3-p2-p1))+p2;} 

    if(dig==1) 
return (x*y); 
} 
int digits(int o) 
{ int c=0; 
    while(o>0){ 
     o=o/10; 
     c++; 
    } 
    return c; 
} 
+1

在gdb中運行它,並在崩潰時查看堆棧跟蹤。 [bt full](https://sourceware.org/gdb/onlinedocs/gdb/Backtrace.html) – 2015-02-10 08:01:37

+0

使用「-Wall」編譯器 - 標誌 – 2015-02-10 08:07:49

+2

「...在這個非常新的,所以無法找出使用GDB的事情「 - 考慮它的激勵。如果不是現在,那是什麼時候* ? – WhozCraig 2015-02-10 08:20:42

回答

2
int d; 

沒有在功能pro()初始化,您使用它,使用undeterminate值導致不確定behvaior。

請在使用前將變量初始化爲合適的值。

FYI的pow()原型是

double pow(double x, double y) 

但我沒有看到雙重使用和傳遞的int這個API並存儲在INT返回值,所以你可能無法得到預期的,因爲類型的結果錯配

2

這看起來很奇怪

int pro(int x,int y) 
{ 
    ... 
    if(dig==1) 
    return (x*y); 
} 

如果不爲1,返回任何值是在棧上。

我建議你用gcc和warn-all編譯器標誌(-Wall)編譯。

相關問題