【发布时间】: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, &volume, &surfaceArea)){,但这只是一个怀疑。 -
不相关:在
bool calculateBox(double length, double width, double height, double * volume, double * surfaceArea)中考虑使用引用而不是指针:bool calculateBox(double length, double width, double height, double & volume, double & surfaceArea)引用通常比指针更容易使用,也更难搞砸。 -
@user4581301 伙计,你是个天才。我最初说过 if ((calculateBox(length, width, height, &volume, &surfaceArea)) = true){ 但现在我明白了返回值本身实际上是真的。这实际上解决了我所有的问题,非常感谢!
-
至于第二点,我同意这会更容易使用,但当前项目概述了“在 c++ 解决方案中使用指针”。不过感谢您的提醒!
标签: c++ function if-statement boolean