gpt4 book ai didi

c - 新的 C 学习者。为什么下面的代码不起作用。我得到关于英尺和英寸的错误答案

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:58 25 4
gpt4 key购买 nike

我正在尝试运行此程序以将米转换为英尺和英寸。使用3米 例如,我的高度应该是 9 英尺 10.11 英寸。我是新手并尝试使用 fgets 并且仍在努力使用 modf 作为任务来完成它。在下面的代码中 我正在使用 modff,因为它被推荐与浮点变量一起使用。

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

void metersToFeetAndInches(double meters, unsigned int *feetPtr, double *inPtr)
{
float rawfeet = meters * 3.281;
float feet;
double rawinches = modff(rawfeet, &feet);


if (feetPtr){
printf("Storing %1.0f to feet at the address %p\n", feet, feetPtr);
feet= *feetPtr;
}

if (inPtr){
printf("Storing %0.5f to inches at the address %p\n", rawinches, inPtr);
*inPtr = rawinches;}

}
int main(int argc, const char * argv[])
{

double meters;
double inches;
unsigned int feet;

printf("How many meters are you trying to convert?\n");

scanf("%lf%*[^\n]",(&meters), stdin);


metersToFeetAndInches(meters, &feet, &inches);
printf("%1.0f meters is equal to %u feet and %.3f inches.\n", meters,feet, inches);
return 0;
}

最佳答案

试试这个:

#include "stdio.h"
#include "math.h"

void metersToFeetAndInches(float meters, float *feetsPtr, float *inchesPtr)
{
*inchesPtr = modff(meters * 3.28084, feetsPtr) * 12;
}


int main()
{
float meters;
float feet;
float inches;

printf("How many meters are you trying to convert?\n");
fscanf(stdin, "%f%*[^\n]", &meters);

metersToFeetAndInches(meters, &feet, &inches);
printf("%.3f meters is equal to %1.0f feet and %.3f inches.\n",
meters, feet, inches);
return 0;
}

一些说明:

  • 最好始终使用相同的单位进行计算(此处为 float )。
  • 您忘记将小数英尺转换为英寸。

关于c - 新的 C 学习者。为什么下面的代码不起作用。我得到关于英尺和英寸的错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049452/

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