c++ - 如何在C++中输出一个数字乘以另一个变量的值的双精度值? [英] How to output a double that is the value of a number multiplied by another variable in C++?
问题描述
我正在尝试使用 double
为我的 weight_Fee
获取输出,但我似乎无法获得正确的值.我曾尝试使用 float
,但我也无法让它工作.
I'm trying to get an output for my weight_Fee
using double
, and I cannot seem to get the correct value. I have tried using float
, but I haven't been able to get that to work either.
我的目标是获得一个包含两位小数的输出值,就像我要计算成本一样,但我每次都得到 0.00.
My goal is to get an output value containing two decimal places as if I were to be calculating a cost, but I get 0.00 every time.
我是 C++ 的新手,所以如果有人能告诉我我做错了什么,那将是一个很大的帮助.谢谢.
I'm new to C++, so if anyone can tell me what I'm doing wrong, it would be a big help. Thanks.
#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;
}
推荐答案
double weight_Fee = 0.5 * animal_Weight;
当您像这样初始化 weight_Fee
时,您将其设置为等于 0.5 *animal_Weight 的当前值.由于这是当前未定义的 weight_Fee
将是一些垃圾值.
When you initialize weight_Fee
like that you are setting it equal to 0.5 * the current value of animal_Weight. Since this is currently undefined weight_Fee
will be some garbage value.
当您稍后根据用户输入将 animal_Weight
设置为某些内容时,不会更改先前变量的值.您必须再次使用该语句来设置 weight_Fee
= 0.5 * animal_Weight
When you set animal_Weight
to something based on user input later on, that won't change the value of a previous variable. You'll have to use that statement again to set weight_Fee
= 0.5 * the current value of animal_Weight
最好的做法可能是在顶部声明 weight_Fee
,并且在您将 animal_Weight
设置为您想要的值之前不要定义它.
The best thing to do is probably to just declare weight_Fee
at the top, and not define it until you have set animal_Weight
to what you want it to be.
像这样:
#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;
}
这篇关于c++ - 如何在C++中输出一个数字乘以另一个变量的值的双精度值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!