2016-09-29 54 views
0

我在C++中做了BMI计算,并决定我想添加一个计算每周体重变化的用户新BMI的部分(比如每周减掉2磅,或者每周增加2磅,n周)我有两个if语句,所以当被问及他们在寻找什么样的重量变化时,基于这个结果,它会跳到一个if语句或另一个语句。我的意思是,如果用户想要重量,他们会把-2,这将跳转到我为减肥设置的if语句。如果用户想要GAIN权重,它会跳转到另一个if语句,设置为计算新的BMI并给定新的权重变化。这里是我的两个if语句设置:C++如果语句导致CMD不发布输出?

#include "stdafx.h" 
#include <iostream> // Allows us to use cout and cin 
#include <cmath> // To allow us to calculate the BMI 
#include <iomanip> // Set specific decimal points(two) 
using namespace std; 

int main() 
{ 
double weight; 
cout << "What is your current weight?: "; // Using the cout() function, we get user input 
cin >> weight; 
double heightFeet; 
cout << "What is your height(in feet, just the first part(Example, if you're 5'11, put 5)"; 
cin >> heightFeet; 
double heightInches; 
cout << "What is your height in inches, just the second part(Example if you're 5'11, put 11)\n"; 
cin >> heightInches; 
double HeightConverter = 12 * heightFeet + heightInches; 
cout << "Your height in inches is: " << HeightConverter << "\n"; 
double BMICalc = (weight * 703)/(pow(HeightConverter, 2)); 
std::cout << std::fixed; 
std::cout << std::setprecision(2); 
std::cout << "Your current BMI is: " << BMICalc << "\n"; 
double GoalWeight; 
std::cout << "What is your goal weight change per week? (lb)\n"; 
cin >> GoalWeight; 
if (GoalWeight >= 0) { 
    int weeks; 
    cout << "How many weeks do you plan to continue this trend?\n"; 
    cin >> weeks; 
    double PosBMI = (weight + GoalWeight) * 703/(pow(HeightConverter, 2)); 
    cin >> PosBMI; 
    cout << "If you complete your plan for " << weeks << "weeks you will have a new BMI of: \n" << PosBMI; 

} 
if (GoalWeight < 0) { 
    int weeks; 
    cout << "How many weeks do you plan to continue this trend?\n"; 
    cin >> weeks; 
    double NegBMI = (weight - GoalWeight) * 703/(pow(HeightConverter, 2)); 
    cin >> NegBMI; 
    cout << "If you complete your plan for " << weeks << "weeks you will have a new BMI of: \n" << NegBMI; 
} 
system("pause"); 
return 0; 

} 

当这个被编译,它得到“多少周做你打算继续这一趋势?”,如果我输入3,它会在终端暂停3,并且什么都不做,最终我必须关闭它。有没有人看到这个问题在if语句中是什么?对于丑陋的代码,以及提前抱歉。在这里忍受我。

回答

1

PosBMI被声明和初始化,然后立即被std :: cin调用覆盖的大问题。类似的NegBMI问题。

double PosBMI = (weight + GoalWeight) * 703/(pow(HeightConverter, 2)); 
cin >> PosBMI; 

然后,当然,重量没有宣布......我认为你需要先得到这个编译。

所有这一切,我想补充一点,我的个人BMI需要工作。

我想,你的代码更可能应该是(伪codish这里)

cout << "Enter your weight"; 
cin >> weight; 
cout << "Enter Goal" 
cin >> WeightGoal 

if (WeightGoal > weight) { 
    ..... 
} else { 
    .... 
} 
cout << "If you complete your plan for " << weeks << ..... 
+0

我应该添加的每个的std :: CIN打电话到他们的尊重if语句?我会认为我仍然需要两个?或者我只需要一个cin语句? – Xor

+0

weight实际上是声明的,它只是从OP中的代码中省略,它只是用于计算原始BMI,如果它是全局变量,它应该仍然可以在范围外访问,对吗? – Xor

+0

我认为你只想问一次。我相信你的GoalWeight确实是“重量> GoalWeight”的情况,反之亦然。 –