【问题标题】:How to output a double that is the value of a number multiplied by another variable in C++?如何在 C++ 中输出一个数字乘以另一个变量的值的双精度数?
【发布时间】:2018-02-17 22:36:27
【问题描述】:

我正在尝试使用double 为我的weight_Fee 获取输出,但我似乎无法获得正确的值。我试过使用float,但我也无法让它工作。

我的目标是获得一个包含两位小数的输出值,就像我要计算成本一样,但我每次都得到 0.00。

我是 C++ 新手,所以如果有人能告诉我我做错了什么,那将是一个很大的帮助。谢谢。

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {

double animal_Weight;   
double weight_Fee = .5 * animal_Weight;

cout << "In rounded poundage, how much does your animal weigh? ";
cin >> animal_Weight;

cout << setprecision (2) << fixed << weight_Fee;

return 0;
}

【问题讨论】:

  • 变量animal_Weight是未定义的,可以被编译器或操作系统初始化为任何值,或者内存中的任何值。
  • 另外,输入数据后,weight_Fee 不会再次计算。我建议将weight_Fee 的定义移到输入animal_Weight 之后。
  • 语句按顺序执行。您如何期望乘法在您要求输入之前起作用?

标签: c++ variables floating-point double output


【解决方案1】:
double weight_Fee = 0.5 * animal_Weight;

当您像这样初始化 weight_Fee 时,您将其设置为等于 0.5 * animal_Weight 的当前值。由于这是当前未定义的 weight_Fee 将是一些垃圾值。

当您稍后根据用户输入将animal_Weight 设置为某个值时,这不会更改先前变量的值。您必须再次使用该语句来设置 weight_Fee = 0.5 * animal_Weightcurrent

最好的办法可能是在顶部声明weight_Fee,直到您将animal_Weight 设置为您想要的为止,然后再定义它。

类似这样的:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {

    double animal_Weight;   
    double weight_Fee;

    cout << "In rounded poundage, how much does your animal weigh? ";
    cin >> animal_Weight;

    weight_Fee = .5 * animal_Weight

    cout << setprecision (2) << fixed << weight_Fee;

    return 0;
}

【讨论】:

    【解决方案2】:

    变量animal_Weight 是未定义的,可以由编译器或操作系统初始化为任何值,也可以是内存中最后出现的任何值。

    你需要在输入animal_Weight的值后计算weight_Fee

    double animal_Weight = -1.0;   
    
    cout << "In rounded poundage, how much does your animal weigh? ";
    cin >> animal_Weight;
    double weight_Fee = .5 * animal_Weight;
    
    cout << setprecision (2) << fixed << weight_Fee;
    

    【讨论】:

      【解决方案3】:

      有人忘了告诉你,你的计算机一次只执行一条指令(并且 C++ 编译器会按照与你的代码相对应的顺序生成指令);或者你可能从来没有理解过这个声明。

      1) double animal_Weight;   
      2) double weight_Fee = .5 * animal_Weight;
      
      3) cout << "In rounded poundage, how much does your animal weigh? ";
      4) cin >> animal_Weight;
      
      5) cout << setprecision (2) << fixed << weight_Fee;
      

      您的代码提示输入 (3) 和 cin 的 (4) 动物重量。好的。

      但是 weight_Fee 是在知道 animal_Weight (4) 之前计算的 (2)。这是一个逻辑错误。

      因此,如果 (2) 处的计算不知道 animal_Weight,则根本无法确定正确的值。

      此外,animal_Weight (1) 未初始化,从而产生未定义的行为。


      请注意,您可以让编译器抱怨(生成警告)尝试使用未初始化的变量(在第 2 行),但您必须命令编译器这样做(通过使用选项)。

      【讨论】:

        猜你喜欢
        • 2013-02-11
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-09
        • 1970-01-01
        相关资源
        最近更新 更多