函数中modf()的问题

时间:2014-11-08 13:32:05

标签: c function

我正在尝试创建一个函数,在modf()的帮助下将值拆分为两个单独的值。我希望能够将米转换成英尺和英寸,我知道我应该怎么做但我似乎无法使用函数。

#include <stdio.h>
#include <math.h>

void metersToFeetAndInches(double meters, double feet, double inches, double feetTotal)
{
    feetTotal = meters * 3.281;
    inches = modf(feetTotal, &feet);
    inches = inches * 12.0;
}

int main(int argc, const char * argv[])
{
    //With function

    double meters = 3.0;
    double feet;
    double inches;
    double total;

    metersToFeetAndInches(meters, feet, inches,  total);
    printf("%.1f meters is equal to %f feet and %.1f inches.\n", meters, feet, inches);

    //Without function

    double meters1 = 3.0;
    double feet1;
    double inches1;

    double total1 = meters1 * 3.281;

    inches1 = modf(total1, &feet1);

    inches1 = inches1 * 12.0;

    printf("The first number is %.0f and the second number is %.1f\n", feet1, inches1);

    return 0;
}

这就是结果:

3.0 meters is equal to 0.000000 feet and 0.0 inches.
The first number is 9 and the second number is 10.1

有人可以解释我在这里做错了吗?因为我无法理解。

2 个答案:

答案 0 :(得分:2)

两个问题:通过引用传递和单位分割。

OP的第一种方法可以通过传递main()的{​​{1}}和feet的地址来解决。

inches

但是由于在#define meter_per_foot (1000/(12*25.4)) #define inch_per_foot 12 void metersToFeetAndInches(double meters, double *feet, double *inches) { double feetTotal = meters * meter_per_foot; feetTotal = meters * 3.281; *inches = modf(feetTotal, feet) * inch_per_foot; } ... metersToFeetAndInches(meters, &feet, &inches); 中打印了一个圆形inches,输出可能会像“10英尺12.0英寸”。

而是转换为最小的兴趣单位,在这种情况下为0.1英寸。

printf("The first number is %.0f and the second number is %.1f\n", feet1, inches1);

答案 1 :(得分:1)

修改后的代码:

#include <stdio.h>
#include <math.h>

void metersToFeetAndInches(double *meters, double *feet, double *inches, double *feetTotal)
{
    *feetTotal = *meters * 3.281;
    *inches = modf(*feetTotal, feet);
    *inches = *inches * 12.0;
}

int main(int argc, const char * argv[])
{
    //With function

    double meters = 3.0;
    double feet;
    double inches;
    double total;

    metersToFeetAndInches(&meters, &feet, &inches,  &total);
    printf("%.1f meters is equal to %f feet and %.1f inches.\n", meters, feet, inches);
}

修改函数中的某些内容不会修改main中变量的值。这就是为什么你需要使用指针,因为它们包含变量的地址,这样当你修改它们时函数,main中变量的值也会发生变化。变量名前的&将给出它的地址。这称为Pass by Reference。您正在执行Pass by Value