Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++新手问题_C++ - Fatal编程技术网

C++新手问题

C++新手问题,c++,C++,我的任务: 编写以下程序:要求用户输入2个浮点数,使用双精度。然后要求用户输入以下数学符号之一:+、-、*、或/。程序根据用户输入的两个数字计算答案并打印结果。如果用户输入了无效符号,则程序不应打印任何内容 我的代码: #include <iostream> using namespace std; int introducir() { int a; cin >> a; return a; } bool simbolo(char x) {

我的任务:

编写以下程序:要求用户输入2个浮点数,使用双精度。然后要求用户输入以下数学符号之一:+、-、*、或/。程序根据用户输入的两个数字计算答案并打印结果。如果用户输入了无效符号,则程序不应打印任何内容

我的代码:

#include <iostream>

using namespace std;

int introducir()
{
    int a;
    cin >> a;
    return a;
}

bool simbolo(char x)
{
    if (x == '+')
        return true;
    if  (x == '-')
        return true;
    if (x == '*')
        return true;
    if (x == '/')
        return true;
    return false;    
}

void operar(char x, int a, int b)
{
    if (x == '+')
        cout << a+b;
    if  (x == '-')
        cout << a-b;
    if (x == '*')
        cout << a*b;
    if (x == '/')
        cout << a/b;
    else cout << "INVALID OPERATION SIMBOL";

}

int main()
{
    cout << "insert 2 numbers"<< endl;
    int a =introducir();
    int b= introducir();
    cout << "introduce one of these simbols : +,-,* o /." << endl;
    char x;
    cin >> x;
    bool primo= simbolo(x);
    {
        if (primo) {
            cout << "simbol is valid" << endl;
        } else {
            cout << "invalid simbol" << endl;
        }
        cout << "operation result is:";
   }
   operar(x,a,b);
}

如果符号不在+、-、*、/,我希望它返回一条消息INVALID OPERATION SIMBOL;但是,即使符号有效,它也会返回它。如何解决这个问题?

按照您编写的方式,else只适用于最后的if

改为

if (x == '+'){
    cout << a+b;
} else if  (x == '-'){
    cout << a-b;
} else if (x == '*'){
    cout << a*b;
} else if (x == '/'){
    cout << a/b;
} else { 
    cout << "INVALID OPERATION SIMBOL";
}

其他if语句也类似。你甚至可以考虑重构到一个交换块。大括号不是完全必要的,但为了清楚起见,我已经把它们放进去了。

如果有switch语句,请查阅其他语句。现在是开始学习如何使用调试器的好时机。说真的,从长远来看,这会给你带来巨大的好处;这可能是一个非常基本的问题,但它包括再现问题的完整代码以及对预期行为的描述。“这不是世界上最伟大的问题,但我认为它不值得这么多的否决票。”杰斯珀朱尔将鼠标悬停在否决票按钮上,看看工具提示。没有显示出任何研究成果非常适合这个问题。