2017-02-17 51 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谢谢。添加了对我的答案的建议 –