c - 简单的 C 程序无法正确计算

标签 c math

所以,我对编程完全陌生,我正在学习 C 语言编程。我正在尝试用 C 语言编写一个简单的程序来计算佣金,如下

#include<stdio.h>
int main()
{
    float fRate, fSales_Price, fCost, fCommission;

    printf("\nEnter your commission rate: ");
    scanf("%.2f",&fRate);
    printf("\nEnter the price of the item sold: ");
    scanf("%.2f", &fSales_Price);
    printf("\nEnter the original cost of the item: ");
    scanf("%.2f", &fCost);

    fCommission = (fRate / 100) * (fSales_Price - fCost);

    printf("\nYour commission is: %.2f", fCommission);
}

每当我尝试运行它时,都会发生两件事。首先,如果我尝试在程序中输入任何小数,例如如果我说汇率是 12.5,它会立即跳过其他输入并完成程序,说佣金是 0.00。如果我忽略小数,程序会正常运行直到最后,此时我仍然获得 0.00 的佣金。有什么建议吗?

最佳答案

你的格式说明符是错误的,如果你这样做,你必须使用编译器警告,那么你就不会问这个,因为该格式说明符无效,你不能用 scanf()< 限制小数位数 它已经在 SO 的许多问题中讨论过,更重要的是你不需要,而且它没有意义,所以只需从格式说明符中删除 .2 ,而是,在使用这些值之前检查 scanf() 是否成功。

关于c - 简单的 C 程序无法正确计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30493940/

相关文章:

检查 C 字典中的单词

c - 为 stdin、stdout 和 stderr 定义和初始化数组

c - 在 C 中围绕元音旋转单词

javascript - 根据给定的坐标、宽度和高度查找矩形顶点

python - 寻找更好的方法来计算矩阵

c# - 复杂路径

c - GLFW 窗口无法打开(Ubuntu)

c - 使用 GTK+2 时收到 “format not a string literal and no format arguments” 警告

Java:多次设置int值

dart - 为什么 floor() 在 Dart 中四舍五入?