切换语句不起作用 c++ 和 D:\c++ dev-c\Makefile.win 目标"abc.o"的配方失败



所以,我继续用 c++ 处理我的 abc 公式,再一次,一些错误弹出:D

这就是我现在拥有的:

#include <iostream>
#include <cmath>
using namespace std;
class abcformule{
    public:
        int discriminant(double a, double b, double c) {
            return pow(b, 2) - 4 * a *c;
        }
        void answer(double a2, double b2, double c2) {
            int D = discriminant(a2, b2, c2);
            switch(D) {
                case < 0:
                    cout << "Discriminant is lower than 0, no solutions for x.";
                    cout << endl;
                    break;
                case > 0:
                    cout << "Discriminant is bigger than 0, two solutions for x: ";
                    cout << endl; 
                    cout << "x = " << (-b2 + sqrt(D)) / (2 * a2) <<
                            " or " << (-b2 - sqrt(D)) / (2 * a2) << 
                            "." << endl;
                    break;
                case = 0:
                    cout << "Discriminant is 0, only one solution for x: " << endl;
                    cout << (-b2) / (2 * a2) << endl;
            }
        }
};
int main(int argc, char** argv) {
    abcformule abc;
    abc.answer(5, -2, -7);
    return 0;
}

这些是错误:

D:c++ dev-cabc.cpp    In member function 'void abcformule::answer(double, double, double)':
14  10  D:c++ dev-cabc.cpp    [Error] 'D' cannot appear in a constant-expression
18  10  D:c++ dev-cabc.cpp    [Error] expected primary-expression before '>' token
25  10  D:c++ dev-cabc.cpp    [Error] expected primary-expression before '=' token
25  12  D:c++ dev-cabc.cpp    [Error] an assignment cannot appear in a constant-expression

我该如何解决这个问题?哦,我也看到错误日志中弹出了这个东西:

28      D:c++ dev-cMakefile.win   recipe for target 'abc.o' failed

我更喜欢你使用 if else 而不是 switch,因为你不能在 switch 的情况下进行比较

#include <iostream>
#include <cmath>
using namespace std;
class abcformule{
public:
    int discriminant(double a, double b, double c) {
        return pow(b, 2) - 4 * a *c;
    }
    void answer(double a2, double b2, double c2) {
        int D = discriminant(a2, b2, c2);
            if(D<0){
                cout << "Discriminant is lower than 0, no solutions for x.";
                cout << endl;
            } else if(D>0){
                cout << "Discriminant is bigger than 0, two solutions for x:     ";
                cout << endl; 
                cout << "x = " << (-b2 + sqrt(D)) / (2 * a2) <<
                        " or " << (-b2 - sqrt(D)) / (2 * a2) << 
                        "." << endl;
            } else{
                cout << "Discriminant is 0, only one solution for x: " <<          endl;
                cout << (-b2) / (2 * a2) << endl;
            }   
    }
};
int main(int argc, char** argv) {
    abcformule abc;
    abc.answer(5, -2, -7);
    return 0;
}

最新更新