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

lul*_*laz 1 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);
}

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Gri*_*han 5

scanf()函数的调用是错误的,忘了&:

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

应该:

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

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

switch(calctype){
 case 'S' :  /* First if code 
             */
            break;
 case 'P':  /*  Second if code
            */
            break;
}
Run Code Online (Sandbox Code Playgroud)

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

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

另请注意不要使用void main(),根据C标准主要定义为int main(void),as int main(int argc, char *argv[]).阅读C和C++ 应该main()返回什么?.