简单的C代码编译但在给定输入时崩溃

时间:2013-10-19 11:45:10

标签: c windows crash

我写了这个非常简单的代码来查找电阻值。代码将编译并询问初始问题,但是当输入P或S的输入时,代码崩溃并退出。任何帮助都会很棒,我知道这将是非常简单的我错过了...

#include <stdio.h>

void main ()
{
float res1;
float res2;
float res3;
float answer;
char calctype;

printf("Please enter 1st resistor value:");
   scanf("%f", &res1);

printf("Enter 2nd resistor value:");
   scanf("%f", &res2);

printf("Enter 3rd resistor value:");
   scanf("%f", &res3);

puts("type P for Parallel calculation or S for Series calculation:\n");
scanf("%c", calctype);

if (calctype == 'S') {
answer = res1 + res2 + res3;
printf("The Series value is:%f \n", answer);
}
else if (calctype == 'P') {
answer = 1/(1/res1 + 1/res2 + 1/res3);
printf("The Parallel Value is:%f \n", answer);
}

}

谢谢!

2 个答案:

答案 0 :(得分:5)

scanf()函数调用错误,忘记&

scanf("%c", calctype);
// calctype is declared as char variable you need address of it  

应该是:

scanf("%c", &calctype);
 //         ^ added & - pass by address to reflect change  

一面注意:
使用switch-case而不是if-else-if。

switch(calctype){
 case 'S' :  /* First if code 
             */
            break;
 case 'P':  /*  Second if code
            */
            break;
}

一般来说,使用平面编码结构是优选的编码实践,然后嵌套if-else。

您还需要改进代码中的缩进,阅读Indenting C Programs。这也将告诉你一些好的编码实践。

另请注意,请勿使用void main(),根据C标准,主要定义为int main(void)int main(int argc, char *argv[])。阅读What should main() return in C and C++?

答案 1 :(得分:0)

使用

scanf("%c", &calctype); /* put ampersand before variable name */

取代

scanf("%c", calctype);