无论输入如何,C ++程序都提供相同的输出

时间:2014-09-10 00:04:21

标签: c++

我正在编写一个程序,它从用户那里获取包的重量和尺寸。如果重量大于或等于27,则应显示包装太重。如果尺寸大于或等于0.1米立方,则应显示包装太大。出于某种原因,下面的代码运行正常,但无论我键入什么值,它总是输出"拒绝:太大太重。"谁能告诉我为什么会这样?我在一个入门编程课程中,所以我认为这是一个我忽略的小错误。

谢谢!

#include <iostream>

using namespace std;

double weight;
double length;
double width;
double height;
double dimensions;
bool weight_passed;
bool dimensions_passed;

int main()
{
    cout << "Enter the weight of the package in kilograms: ";
    cin >> weight;
    cout << "Enter the length of the package in meters: ";
    cin >> length;
    cout << "Enter the width of the package in meters: ";
    cin >> width;
    cout << "Enter the height of the package in meters: ";
    cin >> height;
    dimensions = length * width * height;
    if (weight >= 27)
        weight_passed = false;
    if (dimensions >= 0.1)
        dimensions_passed = false;

    if (dimensions_passed == false && weight_passed == false)
        cout << "Rejected: Too big and too heavy." << endl;
    else if (dimensions_passed == true && weight_passed == false)
        cout << "Rejected: Too heavy." << endl;
    else if (dimensions_passed == false && weight_passed == true)
        cout << "Rejected: Too big." << endl;
    else
        cout << "Accepted!" << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:2)

您需要初始化变量,尤其是在这种情况下的bool

bool weight_passed = true;
bool dimensions_passed = true;

答案 1 :(得分:0)

如果weight_passedweight < 27是什么?什么是dimensions_passed,如果dimensions < 0.1?他们没有被分配 - 因此是不确定的。你需要像这样初始化它们:

bool weight_passed = true;
bool dimensions_passed = true;

您可以在声明或main()

中执行此操作

或者,您可以在else上添加if

if (weight >= 27)
    weight_passed = false;
else
    weight_passed = true;

if (dimensions >= 0.1)
    dimensions_passed = false;
else
    dimensions_passed = true;

既然你是新手,我会给你一些其他提示。每个if的括号内的部分可以像布尔值一样对待。所以你可以这样做:

weight_passed = (weight < 27); // equivalent to !(weight >= 27)
dimensions_passed = (dimensions < 0.1); // equivalent to !(dimensions >= 0.1)

这不仅会给你相同的结果,还会保证你的变量被分配。

最后一件事:因为进入if条件的是布尔逻辑,所以你不必使用那些相等运算符(==):

if (!dimensions_passed && !weight_passed)
    // BOTH too big AND too heavy. Geez, see a doctor man.
else if (dimensions_passed)
    // dimensions pass though, so must just be too heavy
else if (weight_passed)
    // weight_passed, so must just be too big
else
    // Goldilocks would say this one is just right.