【问题标题】:C++ Boolean Function OperandsC++ 布尔函数操作数
【发布时间】:2018-05-13 19:11:06
【问题描述】:

所以我开始在我的大学课程中使用 c++,并且到目前为止进展顺利。我在当前问题上遇到了两难境地,我已经弄清楚了基本的代码结构,我的输出只有一个问题。

我在寻找什么,例如;

if (bool variable = true){ 

  output

else
  alternate output

我知道这不是一个免费的调试服务场所,但它对我未来的项目也很有帮助,而且没有任何错误,它执行得很好。

我的代码:

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

//function prototypes
bool calculateBox(double, double, double, double *, double *);

int main()
{
    //defining variables
    double length, width, height, volume, surfaceArea;

    cout << "Hello and welcome to the program.\nPlease enter the dimensions for the box in [cm](l w h): ";
    cin >> length >> width >> height;
    calculateBox(length, width, height, &volume, &surfaceArea);

    if (bool calculateBool = true) {
        cout << "Volume: " << volume << "cm^3" << endl << "Surface Area: " << surfaceArea << "cm^2" << endl;
    }
    else
        cout << "Error, value(s) must be greater than zero!" << endl;

    system("pause");
    return 0;
}

//functions
bool calculateBox(double length, double width, double height, double * volume, double * surfaceArea) {
    if ((length > 0) && (width > 0) && (height > 0)) {
        *surfaceArea = length * width * 6;
        *volume = length * width * height;
        return true;
    }
    else
        return false;
}

*Key,如果值符合要求,输出显示的不是错误信息,而是一个奇怪的表面面积和体积字符串。它似乎跳过了“else”语句。

我的问题 - 我的错误是否存在于函数的返回语句中?还是我在 main 方法中的“if”语句存在逻辑问题?

【问题讨论】:

  • 您的if 条件始终评估为真。你这样做是什么意思?
  • if (bool calculateBool = true) 创建一个新变量 calculateBool,并将其初始化为 true。不是你想要的。我怀疑你想要的更像if (calculateBox(length, width, height, &amp;volume, &amp;surfaceArea)){ ,但这只是一个怀疑。
  • 不相关:在bool calculateBox(double length, double width, double height, double * volume, double * surfaceArea) 中考虑使用引用而不是指针:bool calculateBox(double length, double width, double height, double &amp; volume, double &amp; surfaceArea) 引用通常比指针更容易使用,也更难搞砸。
  • @user4581301 伙计,你是个天才。我最初说过 if ((calculateBox(length, width, height, &volume, &surfaceArea)) = true){ 但现在我明白了返回值本身实际上是真的。这实际上解决了我所有的问题,非常感谢!
  • 至于第二点,我同意这会更容易使用,但当前项目概述了“在 c++ 解决方案中使用指针”。不过感谢您的提醒!

标签: c++ function if-statement boolean


【解决方案1】:

在声明中

if (bool calculateBool = true) 

bool calculateBol 部分将导致名为calculateBool 的局部变量被定义为布尔值。 = true 部分意味着将 = 左侧的内容分配给值 true。因此,整个bool calculateBool = true 将为真,因此永远不会执行 else 子句。

请注意,在某个条件下出现单个= 应始终敲响可能发生不良迹象的钟声。因为比较相等是==

话虽如此,你可以写:

 if (calculateBox(length, width, height, &volume, &surfaceArea)) {

或者如果您稍后需要该值:

bool calculateBool = calculateBox(length, width, height, &volume, &surfaceArea);
if (calculateBool) {  // or calculateBool==true if you prefer

【讨论】:

  • 这是对我的问题的更深入的解决方案。我做错了什么真的很清楚,下次我会知道的。创建局部变量与调用函数似乎是我的主要问题。真的很感激,克里斯托夫!
猜你喜欢
  • 2015-05-23
  • 2014-07-02
  • 2011-08-13
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 2013-12-26
  • 2013-05-06
  • 1970-01-01
相关资源
最近更新 更多