【问题标题】:Simple C code compiles but crashes when given an input简单的 C 代码编译但在给定输入时崩溃
【发布时间】:2013-10-19 11:45:09
【问题描述】:

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

}

谢谢!

【问题讨论】:

    标签: c windows crash


    【解决方案1】:

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

    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标准main要定义为int main(void),为int main(int argc, char *argv[])。阅读What should main() return in C and C++?

    【讨论】:

    • @paxdiablo 已更正谢谢!
    • 哇哇非常感谢你....再次感谢。
    • @LauraStokes 阅读更新的答案,在答案中添加了关于缩进和良好编码实践的链接,阅读它只需 2-3 小时我强烈建议您阅读它
    【解决方案2】:

    使用

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

    代替

    scanf("%c", calctype);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多