【问题标题】:Multiply Variable by Another Variable?将变量乘以另一个变量?
【发布时间】:2010-11-26 22:05:10
【问题描述】:

我有一个需要编写的 C 类程序。该程序要求一个数量,我需要将该数量乘以用户输入的另一个变量。 c类的基本计算器脚本:)

我是这样设置的,

    int qty; //basic quantity var
float euro, euro_result;

//assign values to my float vars
euro = .6896; //Euro Dollars
    euro_result = euro * qty; // Euro Dollars multiplied by user input qty

//start program for user
printf("Enter a quantity: ");

//alow user to input a quantity
scanf("%d", &qty);

printf("Euro:       %f \n", euro_result);

为什么它没有按预期工作?

【问题讨论】:

  • 我在这里看不到问题。我已经对其进行了编辑以反映其真实状态。
  • 只是一个注释..记住在定义变量时初始化变量。以便调试变得更容易。例如,而不是做 int qty;将其定义为 int qty = 0;

标签: c calculator


【解决方案1】:

错误在于该行

euro_result = euro * qty;

需要在qty被读入之后

【讨论】:

    【解决方案2】:

    C 程序中的语句按顺序执行,表达式不以符号方式计算。所以你需要以这种方式重新排序你的语句:

    int qty;
    float euro, euro_result;
    
    euro = .6896; // store constant value in 'euro'
    
    printf("Enter a quantity: ");
    
    scanf("%d", &qty); // store user input in 'qty'
    
    euro_result = euro * qty; // load values from 'euro' and 'qty',
                              // multiply them and store the result
                              // in 'euro_result'
    
    printf("Euro:       %f \n", euro_result);
    

    【讨论】:

    • 啊!所以把它放在用户选择数量之后,它应该可以工作。呃!我太笨了,我什至没有想到这一点。
    • 别担心。这是初学者的常见错误。
    • 初学者?是什么给了它? :)
    • 认为他们很愚蠢是初学者的普遍反应 :-)
    • 是的,当你来自 lisp 时这很常见
    【解决方案3】:

    在用户输入之前,您已将欧元乘以用户给定数量 qty。 它应该如下所示: //euro_result = 欧元 * 数量; //

    //start program for user
    printf("Enter a quantity: ");
    
    //alow user to input a quantity
    scanf("%d", &qty);
    
    euro_result = euro * qty; // Euro Dollars multiplied by user input qty
    
    printf("Euro:       %f \n", euro_result);
    

    就是这样。

    【讨论】:

      【解决方案4】:

      我怀疑你想计算euro_result = euro * qty; 之后你已经收集了数量的值。

      【讨论】:

        【解决方案5】:

        问题是您在用户输入任何数据之前将qty 乘以汇率。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-21
          • 2019-08-31
          • 1970-01-01
          • 2016-01-10
          相关资源
          最近更新 更多