输入后小程序崩溃

时间:2019-07-25 17:44:55

标签: c

我绝对不熟悉C语言和计算机科学。我仍在学习如何编码。下面是我编写的一个小程序,该程序将以厘米为单位的高度转换为英尺和英寸,但是,在将height_cm作为输入之后,终端崩溃了。我想了很久,但想不通背后的原因。

#include <stdio.h>
int main(void)
{
    float height_cm;
    float feet=(int)(height_cm/2.54)/12;
    float inch=(height_cm/2.54);

    while(height_cm > 0)
    {
        printf("Enter a height in centimeters(<=0 to quit): ");
        scanf("%.2f", &height_cm);
        printf("%.2f = %d feet, %.2f inches", height_cm,feet,inch);
    }
    printf("Bye");
    return 0;
 }

3 个答案:

答案 0 :(得分:4)

您的主要问题:计算height_cmfeet时,您引用的是未分配的变量inches。这将产生未定义的行为,因为该变量中的值为垃圾值。下面的代码片段解决了一些其他问题,例如在%.2f中使用scanf,并执行了所需的逻辑。

#include <stdio.h>
int main(void)
{
    float height_cm; // Currently junk value
    int feet;        // Currently junk value
    float inch;      // Currently junk value

    // Keep calculating feet / inches as long as the entered hight is positive
    do {
        printf("Enter a height in centimeters(<=0 to quit): ");
        scanf("%f", &height_cm); // Can only use "%.2f for printf not scanf"
        feet=(int)(height_cm/2.54)/12;
        inch=(height_cm/2.54);

        // Output results
        printf("%.2f = %d feet, %.2f inches", height_cm,feet,inch);
    }
    while (height_cm > 0);

    printf("Bye");

    return 0;
 }

答案 1 :(得分:0)

您正在为%d变量(显然是feet)指定float,尽管很奇怪,它是基于舍入值的float,因此您可以使用int(如果需要)。

打开诸如-Wall之类的警告,以警告诸如此类的简单错误。

您还需要检查未初始化的变量,因为这些是崩溃的主要来源。

您不能在未定义的变量上使用while。您必须先定义它。

考虑重组:

float height_cm;

while (true)
{
    printf("Enter a height in centimeters(<=0 to quit): ");
    scanf("%.2f", &height_cm);

    if (height_cm > 0) {
      int feet = (height_cm/2.54)/12;
      float inch = (height_cm/2.54) % 12; // Don't forget to modulo

      printf("%.2f = %d feet, %.2f inches", height_cm,feet,inch);
    }
    else {
      break;
    }
}

由于您要输入和循环输入的方式,您将希望有条件地break,而不是在while本身中表达中断条件。

答案 2 :(得分:0)

正如其他人所述,您正在检查height_cm,然后为其分配值。您可以进行简单的更改,以在将0替换为while循环之前,至少在检查do ... while之前执行一次循环:

    #include <stdio.h>
    int main(void)
    {
    float height_cm;
    float feet=(int)(height_cm/2.54)/12;
    float inch=(height_cm/2.54);

    do 
        {
        printf("Enter a height in centimeters(<=0 to quit): ");
        scanf("%.2f", &height_cm);
        printf("%.2f = %d feet, %.2f inches", height_cm,feet,inch);
        } while(height_cm > 0);
    printf("Bye");
    return 0;
    }
相关问题