程序将整数乘以因子10

时间:2014-11-29 14:10:16

标签: c++

编程的第3章:使用C ++的原理和实践 Bjarne Stroustrup要求你“编写一个程序,该程序接受一个操作,后跟两个操作数并输出结果。例如:”

+ 100 3.14 
* 4 5 

这就是我所做的。

#include<iostream>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

// This little program does addition, substraction, multiplication, and division as long as the number of operators doesn't exceed two.

int main()

{

cout << "Bonvole enigu du nombrojn post unu el tiuj ĉi matematikaj operaciloj: +,-, *, or /  \n";
cout << "Please enter two numbers preceded by either of these mathematical operators: +,-, *, or /  \n";

string s;
int a, b;
cin >> s >> a >> b;
    if (s == "+") {
        cout << a + b;
        }
    else if (s == "-") {
        cout << a - b;
        }
    else if (s == "*") {
        cout << a * b;
        }
    else (s == "/"); {
        cout << a / b << "\n";
        }
return 0;
}

结果都错了。

@localhost ~]$ ./a.out 
Bonvole enigu du nombrojn post unu el tiuj ĉi matematikaj operaciloj: +,-, *, or /  
Please enter two numbers preceded by either of these mathematical operators: +,-, *, or /  
+ 2 3 
50
[chetan@localhost ~]$ ./a.out 
Bonvole enigu du nombrojn post unu el tiuj ĉi matematikaj operaciloj: +,-, *, or /  
Please enter two numbers preceded by either of these mathematical operators: +,-, *, or /  
- 3 2 
11
[chetan@localhost ~]$ ./a.out 
Bonvole enigu du nombrojn post unu el tiuj ĉi matematikaj operaciloj: +,-, *, or /  
Please enter two numbers preceded by either of these mathematical operators: +,-, *, or /  
* 2 3 
60
[chetan@localhost ~]$ ./a.out 
Bonvole enigu du nombrojn post unu el tiuj ĉi matematikaj operaciloj: +,-, *, or /  
Please enter two numbers preceded by either of these mathematical operators: +,-, *, or /  
/ 3 2 
1

1 个答案:

答案 0 :(得分:3)

问题在于:

else (s == "/"); {
    cout << a / b << "\n";
    }

这应该是

else if (s == "/") {
    cout << a / b << "\n";
    }

(请注意添加的if和删除的分号。)

您当前的代码可以重新格式化如下:

else {
    (s == "/");
}
cout << a / b << "\n";

else子句实际上是一个无操作,因为它只是一个比较,无论选择的运算符如何,最终的cout语句都是无条件执行的。