gpt4 book ai didi

c - float 是 printf 的错误值

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

我有另一个打印“1.#R”的浮点输出问题,我已经将它缩小到重复值,所以我的问题是如何将值四舍五入到小数点后两位,以便我可以打印该值(但是不使用“%.2f”)。这是我的代码:

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

void tax_deduction( float *total)
{
float taxpercent = 1.20;
float nationalInsurance = 1.175;
*total = *total - 9000;
*total = *total / taxpercent;
*total = *total / nationalInsurance;
*total = *total + 9000;

}

void hourly_rate(float *rate)
{
int weeks = 52;
float hours = 37.5;
*rate = *rate /(float)weeks;
*rate = *rate /hours;
}

int main()
{
float wages;
float hours = wages;
printf("Please enter your wage: \n");
scanf("%f",&wages);
if(wages > 9000){
tax_deduction(&wages);
}
hourly_rate(&hours);
printf("wages after tax and NI: %.2f\n", wages);
printf("wages per month: %.2f\n", wages / 12);
printf("hourly rate: %.2f\n", hours);
return 0;
}

它在运行 hourly_rate 函数后的显示方式有问题,就像我在底部将其编码为 printf("hourly rate: %.2f\n", (wages/52)/37/5); 它有效,但这并不是我真正想要的编码方式。

有人能想到为什么这不能正常工作吗?

最佳答案

您的问题不是 printf。您的问题是由于使用了未初始化的值,您的代码的算法不正确。

float wages; // wages not initialized
float hours = wages; // hours assigned that uninitialized value
printf("Please enter your wage: \n");
scanf("%f",&wages);
if(wages > 9000){
tax_deduction(&wages);
}
hourly_rate(&hours); // hours still not initialized

您未能初始化 hours

我的猜测是您的意思是在读取wages 后初始化hours。因此,将分配给 hours 的代码移到代码中正确定义 wages 的位置。

float wages;
printf("Please enter your wage: \n");
scanf("%f",&wages);
if(wages > 9000){
tax_deduction(&wages);
}
float hours = wages;
hourly_rate(&hours);

您得到的奇怪输出是使用 %.2f 格式打印浮点 NaN 的结果。我还建议您将 if(wages > 9000) 测试移到 tax_deduction 中。正如您目前所拥有的那样,减税代码的那部分已泄漏到调用代码中。

关于c - float 是 printf 的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16099468/

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