【问题标题】:c-cant printf the cost [closed]c-cant printf成本[关闭]
【发布时间】:2012-11-12 07:14:08
【问题描述】:
#include <stdio.h>
#include <conio.h>

int main()
{
 float L=0; //L is litre
 float gallon;
 gallon = 3.785*L;
 char input;
 float cost;

 printf("Hello, welcome to PetrolUpHere!!\n");
 printf("Would u like unleaded or diesel fuel?");
 scanf("%c", &input);
 printf("Enter the litre you want to fuel:");
 scanf("%f", &L);

 switch (input) {
 case 'u' :
 cost = 1.98*gallon;
 printf("The cost is :%f ",&cost);
 break;

 case 'd' :
 cost = 1.29*gallon;
 printf("The cost is :%f ",&cost);
 break;
 }

 getch();
 return 0;
 }

程序无法显示成本结果,仅在我输入完 scanf 语句和 L 值后才显示成本 = 0.0000。我是c程序的新手,希望能得到帮助。谢谢

【问题讨论】:

  • 添加换行符应该可以解决它。否则输出缓冲区不会被刷新。您也可以手动拨打fflush
  • 使用诸如float 之类的二进制浮点类型来计算货币金额不是一个好主意。货币计算的四舍五入是根据参考十进制表示的精确规则定义的。

标签: c printf scanf


【解决方案1】:

你已经用 L 来计算加仑了

float L=0; //L is litre
 float gallon;
 gallon = 3.785*L;  //here gallon is zero already 

所以你得到了

printf("The cost is :%f ",&cost);

输出he cost is :address

那就试试吧

 gallon = 3.785*L; // try this here 
 switch (input) {  

printf("The cost is :%f ", cost);

【讨论】:

    【解决方案2】:

    我认为这是问题所在,加仑为 0:

     float L=0; //L is litre
     gallon = 3.785*L;
    

    您应该在阅读升数后多次:

    float L=0; //L is litre
    float gallon=3.785f;
    ...
    //read liters
    scanf("%f", &L);
    ...
    cost = 1.98f*gallon*L;
    

    【讨论】:

      【解决方案3】:

      有了这行代码:

      float my_var;
      printf("Hi %f", &my_var);
      

      您会将地址打印到 my_var,即:它存储在内存中的位置。不是变量的值。我认为您对此感到困惑,因为您的 scanf 需要一个指向要更新的值的存储位置的指针。对指针做一些阅读,它会更清楚一些。现在的解决方法是将您的 printf 语句更改为:

      float my_var;
      printf("Hi %f", my_var);
      

      此外,您的加仑线需要在用户输入所有内容后移动,否则您只需在程序开始时将其乘以 0,它将保持为零,而不是预期的结果。

      【讨论】:

        【解决方案4】:

        您需要 2 处更改

         gallon = 3.785*L;
        

        需要移到所有scanfs下方

        第二个变化是打印cost 而不是&amp;cost

        【讨论】:

          【解决方案5】:

          你应该写下语句“gallon = 3.785*L;”从用户那里读取 L 后,其他明智的加仑将变为零,因为 L 被初始化为零。因此成本的值也变为零。

          并且还从 printf 语句中删除 '&'。 这次一定会成功的。

          【讨论】:

            猜你喜欢
            • 2023-03-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-03-27
            • 2016-02-05
            • 1970-01-01
            相关资源
            最近更新 更多