gpt4 book ai didi

c - 函数中 modf() 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 07:13:07 24 4
gpt4 key购买 nike

我正在尝试创建一个函数,借助 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

有人可以解释我在这里做错了什么吗?因为我想不通。

最佳答案

两个问题:按引用传递和单元分割。

OP 的第一种方法可以通过传递 main()feetinches 和 round 的地址来修复。

#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);

但是由于在 printf("The first number is %.0f and the second number is %.1f\n", feet1, inches1) 中打印了一个四舍五入的 inches; 输出可能类似于“10 英尺 12.0 英寸”。

而是转换为感兴趣的最小单位,在本例中为 0.1 英寸。

void metersToFeetAndInches10(double meters, double *feet, double *inches) {
double unit = meters * meter_per_foot;
unit *= inch_per_foot * 10;
unit = round(unit);

*inches = modf(unit/(inch_per_foot * 10), feet) * (inch_per_foot * 10);
}

关于c - 函数中 modf() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com