【问题标题】:Why does my condition not work?为什么我的条件不起作用?
【发布时间】:2018-07-21 19:28:30
【问题描述】:

我有以下代码:

#include <iostream>

using namespace std;

int a, b, sqr;
const int P = 3.14; //Later for circles...
string s1; 

class MathsFunctions{
public:
virtual void square(int a, int b)=0;

};

class TriangleFunc: public MathsFunctions{
public:
    void square(int a, int b){
    sqr = (a * b)/2;
    cout << "Square of triangle is: "<< sqr << endl;
    }
};

class RectangleFunc: public MathsFunctions{
public:
    void square(int a, int b){
    sqr = a * b;
    cout << "Square of rectangle is:  "<< sqr << endl;
    }
};

void getNumbers(){
 cout << "Enter the first number:  "<<endl;
 cin >> a;
 cout << "Enter the second number:   "<< endl;
 cin >> b;
}
void chooseTheFigure(){
   cout << "Choose the figure (rectangle or triangle): "<< endl;
   cin >> s1;
}

int main(){

chooseTheFigure();
getNumbers();

if(s1 == "rectangle" || "Rectangle"){
RectangleFunc r;
MathsFunctions * m = &r;
m -> square(a,b);
};

if (s1 == "triangle" || "Triangle"){
    TriangleFunc t;
    MathsFunctions *m = &t;
    m -> square(a,b);
};

}

我创建了一个计算矩形或三角形的平方的程序。 main() 中有一个条件,但最终程序显示了两个结果。我该如何改进?

程序输出截图:

【问题讨论】:

  • 任何使用屏幕阅读器的人都很难阅读该输出。
  • (s1 == "矩形" || s1 == "矩形") (s1 == "三角形" || s1 == “三角形”)
  • @KillzoneKid 谢谢你!我什至无法想象这个错误是如此愚蠢!
  • @MichealO'Dwyer 知道了!谢谢
  • @Nikita 为什么要使用类之间共享的全局变量?你需要学习如何使用成员变量!

标签: c++ function math output


【解决方案1】:

这并不像你认为的那样:

if(s1 == "rectangle" || "Rectangle"){
    RectangleFunc r;
    MathsFunctions * m = &r;
    m -> square(a,b);
};

上面的if-expression被计算为:

if((s1 == "rectangle") || ("Rectangle"))
 // ^^^^^^^^^^^^^^^^^  or  ^^^^^^^^^^

现在,第二部分,"Rectangle" 是一个 string-literal,它隐式转换为有效指针。并且除nullptr 或某个零之类的整数以外的任何指针都会计算为true - 总是。


你可能想写:

if((s1 == "rectangle") || (s1 == "Rectangle")){
    RectangleFunc r;
    MathsFunctions * m = &r;
    m -> square(a,b);
};

----------------------------------------

您的代码中还有一些其他细微差别,例如

  • 在您的基类中没有 vitual 析构函数,并且,

  • 这个:

    const int P = 3.14; //Later for circles...
    

    P 不会保持您期望的值。

【讨论】:

  • 非常感谢!
【解决方案2】:
if(s1 == "rectangle" || "Rectangle"){

当这是真的时,有两个条件,第一个是你所期望的,第二个是你的错误,因为它现在是你在代码中要说的:

1) 输入字符串 s1,与字符串文字“rectangle”比较是否相等返回 true,或者

2) 如果字符串文字“矩形”本身被视为真值。 由于这种转换本质上是“空指针检查”,并且字符串文字永远不会为空,因此这种情况总是为真。

你需要重复测试:

if(s1 == "rectangle" || s1 == "Rectangle"){

【讨论】:

    【解决方案3】:

    1.正如 WhiZtim 指出的,Or 算子需要修正

    if(s1 == "rectangle" || "Rectangle") {...}
    

    将始终为真,因为“矩形”不为空。

    1. 您应该对字符串使用字符串比较函数(参见 strcmpi())

    编辑

    关于字符串函数,看看这个:

    Case-insensitive string comparison in C++

    【讨论】:

    • 谢谢!我明白了。
    • 您的第二点有点问题。 C++ 中没有像 strcmpi 这样的标准函数。其次,如果您的意思是std::strcmp,那么绝对没有上帝的理由为std::string 这样做。如果你需要那种风格,有std::string::compare。对于某些极端情况,它通常比 strcmp 更快。
    • 感谢您指出这一点.. 已经有一段时间没有联系了 :)
    猜你喜欢
    • 2015-02-28
    • 2011-12-20
    • 2013-06-07
    • 2021-12-19
    • 1970-01-01
    • 2012-08-23
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多