C语言 产生整数而不是小数的计算

e4eetjau  于 2023-02-18  发布在  其他
关注(0)|答案(1)|浏览(122)

我有一些代码:

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

int main(void) {
  int amount;
  
  // user input for annual income
  printf("Enter your amount: ");
  scanf("%d", &amount);

  if(amount <= 34000)
    amount = amount * .33;

  double new_amount = (double) amount;
  printf("your calculated amount: %.2f\n", new_amout);

  return 0;
}

我尝试接受一个整数值,然后在计算后将其转换为双精度值,但是当我输入int时,它打印了一个小数,但没有非整数部分。
例如,如果我的金额是19522,我的代码将打印6442.00而不是6442.26。

toe95027

toe950271#

最简单的修复方法是将amount的数据类型更改为double并更新格式字符串,删除new_amount变量,因为它对您没有任何作用。另外,检查scanf()是否成功,否则您可能正在操作未初始化的数据:

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

int main(void) {
    double amount;
    printf("Enter your amount: ");
    if(scanf("%lf", &amount) != 1) {
        printf("scanf failed\n");
        return 1;
    }
    if(amount <= 34000)
        amount *= .33;

    printf("your calculated amount: %.2lf\n", amount);
}

相关问题