m到C语言的英尺和英寸转换程序?

时间:2015-03-29 01:52:54

标签: c

以米为单位输入的值。我想要你的脚和英寸。例如1米或1.80米,但结果总是3英尺和3.37英寸。我尝试cm=m*100但它不起作用。请帮助。

#include <stdio.h>

int main() {
    float inches = 0.0, feet = 0.0, centimeter = 0.0, meter=0.0, FEET2CM = 30.48,
      INCHTOCM = 2.54;

    printf("Enter your input for meter:");
    scanf("%f", &meter);
    centimeter = meter * 100;
    printf("%.f centimeter is equal to ", centimeter);

    if (centimeter >= FEET2CM) {
        while (1) {
            feet++;
            centimeter = centimeter - FEET2CM;
            if (centimeter < FEET2CM)
                break;
        }
    }

    inches = centimeter/INCHTOCM;

    printf("%.2f feet and %.2f inches\n", feet, inches);
    return 0;
}

2 个答案:

答案 0 :(得分:1)

一种好方法是将米转换为英寸。然后从这些英寸计算整个英尺的数量。最后,计算超过英尺的英寸的剩余部分。像这样的东西(不是确切的代码):

int feet, totalInches, remainderInches;

totalInches = (int) (meters * 39.3701);
feet = (int) (totalInches / 12);
remainderInches = totalInches - (feet * 12);

答案 1 :(得分:0)

以下是您发布的代码的清理:

  • 已添加错误检查
  • 已应用固定转换值的正确定义
  • 已应用魔法数字的正确定义

在给定转换值的情况下,此代码完全符合,已经过测试并且工作正常。

#include <stdio.h>
#include <stdlib.h>

#define FEET2CM  (30.48f)
#define INCHTOCM (2.54f)

int main()
{
    float inches     = 0.0f;
    float feet       = 0.0f;
    float centimeter = 0.0f;
    float meter      = 0.0f;

    printf("Enter your input for meter:");
    if( 1 != scanf("%f", &meter) ) { // then, scanf failed
        perror( "scanf failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful
    centimeter = meter * 100.0f;
    printf("%.f centimeter is equal to ", centimeter);

    if (centimeter >= FEET2CM) {
        while (1) {
            feet++;
            centimeter = centimeter - FEET2CM;
            if (centimeter < FEET2CM)
                break;
        } // end while
    } // end if

    inches = centimeter/INCHTOCM;

    printf("%.2f feet and %.2f inches\n", feet, inches);
    return 0;
} // end function: main