1

我编写了这个非常简单的代码来查找电阻值。代码将编译并询问初始问题,但是当输入 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);
}

}

谢谢!

4

2 回答 2

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 更好。

您还需要改进代码中的缩进,阅读缩进C 程序。这还将告诉您一些良好的编码实践。

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

于 2013-10-19T11:46:27.533 回答
0

利用

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

代替

scanf("%c", calctype);
于 2013-10-19T11:48:01.017 回答