c - float 是 printf 的错误值

标签 c function pointers floating-point printf

我有另一个打印“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/

相关文章:

c - 线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x7ffeefc00000)

c - 线程在加入之前退出

c - 这个尝试的特洛伊木马代码有什么作用?

c - 共享相同第一成员的结构 union

c - 尝试取消引用动态分配的指针时出现段错误

c++ - 在 For 循环内切换 - 在 Release 模式下得到奇怪的结果

sql - PostgreSQL 函数从动态表名称返回结果集

C++如何测试函数使其抛出错误?

c - 多个文件中的静态函数

C - 在带有指针的结构的循环中进行 malloc