c - float 输出不正确

标签 c math input floating-point output

我创建了一个程序,该程序接受用户的输入,然后让他们输入他们想要提供该输入的金额,但是当我打印总数和金额时。然而,这是全面回归相同的值(value):即

总计:5.00 食物:5.00 账单:5.00 旅行:5.00 同性恋:5.00

代替:

总计:14.00 食物:2.00 账单:3.00 旅行:4.00 同性恋:5.00

int main(void)
{

float food = 0.00;
float travel = 0.00;
float bills = 0.00;
float fags = 0.00;
float total = 0.00;

float t_food, t_travel, t_bills, t_fags;

char userInput[3];

while(userInput[0] != 'X')
{

    printf("Select option,\nA: Food\nB: Travel\nC: Bills\nD: Fags\nX: Exit\n");
    scanf("%s", userInput);
    if((userInput[0] == 'A') || (userInput[0] =='a'))
    {
        printf("Please enter an amount: ");
        scanf("%f", &food);
        printf("You have entered: %.2f\n", food);
        t_food += food;

    }
    if((userInput[0] == 'B') || (userInput[0] =='b'))
    {
        printf("Please enter an amount: ");
        scanf("%f", &travel);
        printf("You have entered: %.2f\n", travel);
        t_travel += travel;

    }
    if((userInput[0] == 'C') || (userInput[0] =='c'))
    {
        printf("Please enter an amount: ");
        scanf("%f", &bills);
        printf("You have entered: %.2f\n", bills);
        t_bills += bills;

    }
    if((userInput[0] == 'D') || (userInput[0] =='d'))
    {
        printf("Please enter an amount: ");
        scanf("%f", &fags);
        printf("You have entered: %.2f\n", fags);
        t_fags += fags;

    }
    if((userInput[0] =='X') || (userInput[0] =='x'))
    {
        total = t_food + t_fags + t_travel + t_bills;

        printf("Total: %.2f\n", &total);
        printf("Food: %.2f\n", &t_food);
        printf("Travel: %.2f\n", &t_travel);
        printf("Bills: %.2f\n", &t_bills);
        printf("Fags: %.2f\n", &t_fags);
        break;
    }
}
return 0;

有什么想法吗?

最佳答案

改变

    printf("Total: %.2f\n", &total);
    printf("Food: %.2f\n", &t_food);
    printf("Travel: %.2f\n", &t_travel);
    printf("Bills: %.2f\n", &t_bills);
    printf("Fags: %.2f\n", &t_fags);

    printf("Total: %.2f\n", total);
    printf("Food: %.2f\n", t_food);
    printf("Travel: %.2f\n", t_travel);
    printf("Bills: %.2f\n", t_bills);
    printf("Fags: %.2f\n", t_fags); 

听编译器说,

warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘float *’ [-Wformat]

关于c - float 输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448675/

相关文章:

c - opm 多线程有什么问题?

c++ - 如何判断一组坐标是否为正多边形的顶点?

matlab - 如何判断矩阵是否奇异?

java - 如何检查用户输入而不退出错误

javascript - IE 不希望在 TD 上使用 Javascript 动态添加新行

类和 vector 的 C++ 输入运算符重载

c++ - Linux 中的 gettimeofday 函数线程安全吗?

C 中的字符数组旋转错误 - 看不出原因

c - GCC 4.7.2 优化问题

math - 根据约束对矩阵进行归一化