Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

How to output a double that is the value of a number multiplied by another variable in C++?

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.

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.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
double weight_Fee = 0.5 * animal_Weight;

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.

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

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.

Something like this:

#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...