<p class="ordinary-output target-output" style="margin-top: 0px; margin-bottom: 5px; padding-top: 0px; padding-bottom: 0px; line-height: 22px; font-size: 14px; color: rgb(51, 51, 51); font-family: arial;">
</p>Newbie here. Is there a more efficient way to code (see below). Also, if I wanted to prompt the user to use the calculator again, would i have to nest a bool within each IF? Thanks for your help :)
#include <iostream>
using namespace std;
int main()
{
int nSelection;
double var1, var2;
do
{
cout << "Please make a selection: " << endl;
cout << "1) Addition" << endl;
cout << "2) Subtraction" << endl;
cout << "3) Multiplication" << endl;
cout << "4) Division" << endl;
cin >> nSelection;
}
while (nSelection != 1 && nSelection != 2 &&
nSelection != 3 && nSelection != 4);
if (nSelection == 1)
{
cout << "Please enter the first whole number ";
cin >> var1;
cout << "Please enter the second whole number ";
cin >> var2;
cout << "The result is " << (var1+var2) << endl;
}
if (nSelection == 2)
{
cout << "Please enter the first whole number ";
cin >> var1;
cout << "Please enter the second whole number ";
cin >> var2;
cout << "The result is " << (var1-var2) << endl;
}
if (nSelection == 3)
{
cout << "Please enter the first whole number ";
cin >> var1;
cout << "Please enter the second whole number ";
cin >> var2;
cout << "The result is " << (var1*var2) << endl;
}
if (nSelection == 4)
{
cout << "Please enter the first whole number ";
cin >> var1;
cout << "Please enter the second whole number ";
cin >> var2;
cout << "The result is " << (var1/var2) << endl;
}
return 0;
}
一些C++中最常用的运算符算术运算符,加号操作符(+),减运算符(-),乘法运算符(*),和除法运算符(/)。注意所有的算术运算符是二元运算符意味着他们接受两个操作数-一个在每一侧的操作员。这些运营商的四都是在相同的方式,超载。
使用函数重载运算符的朋友
当操作者不修改其操作数,超载运营商的最佳方法是通过朋友函数。的算术运算符的操作数不修改(他们只是产生并返回结果),所以我们将利用友元函数重载运算符的方法在这里。
下面的示例演示如何重载运算符+(+)为了增加两个“分”的对象在一起: