2017-02-17 59 views
-1

我一直在試圖運行我的代碼,但總是與錯誤代碼0000005計劃與0000005

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

void calculate_resistance(char metal, int length, int diameter, float resistivity); 

int main() 
{ 
    int length, diameter; 
    float resistivity; 
    char metal; 
    printf("Enter the name of the metal: "); 
    scanf("%s", &metal); 
    printf("Enter the resistivity: "); 
    scanf("%f", &resistivity); 
    printf("Enter the length: "); 
    scanf("%d", &length); 
    printf("Enter the diameter: "); 
    scanf("%d", &diameter); 
    calculate_resistance(metal, length, diameter, resistivity); 
    return 0; 
} 

void calculate_resistance(char metal, int length, int diameter, float resistivity) 
{ 
    float radius = diameter/2; 
    float area_of_wire = (M_PI) * pow(radius,2) * length; 
    float resistance = resistivity * length/area_of_wire; 
    printf("Resistivity of %s is %f", metal, resistance); 
} 

我發現,如果我註釋掉的「printf(」%S的電阻率是%F結束」,金屬崩潰, 抵抗性);」或在最後一次scanf後的任何printf它不會崩潰與錯誤代碼0xC0000005

+1

'char metal;' - >'char metal [96];'(適當大小),'void calculate_resistance(char metal [],' – BLUEPIXY

回答

0
char metal; 
printf("Enter the name of the metal: "); 
scanf("%s", &metal); 

此代碼調用未定義的行爲。您正試圖將字符序列存儲在一個char變量中。您應該使用%c格式說明符或一組字符。

0

可變金屬是一個字符。這隻有1個字符。您需要保存一組字符。

char metal[100]; 

當然100的可能不利於你的情況,但使用scanfchar%sprintf會導致一些問題。

2
char metal; 

聲明瞭char。它只能存儲一個個字符。您想存儲一組字符,即字符串。因此,使用

char metal[50]; /* Can store a max of 49 chars +1 for the \0 */ 

之後,從

scanf("%s", &metal); 

離開了&因爲數組名被轉換成一個指向它的第一個元素了。爲了增加安全性,可以防止在格式說明一個長度修改表示的最大字符數減1(爲NUL終止子保留1個空間):

scanf("%49s", metal); 

此外,你應該提供一些更錯誤檢查和通過查看其返回值,檢查所有scanf是否成功。 不要忘記在函數聲明和定義中更改char metalchar metal[]char* metal,因爲您不是傳遞單個字符,而是數組(實際上是指向其第一個元素的指針,因爲數組「衰減」)。

+0

@MM謝謝。添加了對我的答案的建議 –