使用c ++代码的小型计算器

时间:2016-01-29 02:16:22

标签: c++ visual-c++

我正在学习C ++并且我有一个使用if,else if语句创建小型计算器的分配。程序应该像这样工作。首先你需要选择add或substract这样的操作然后输入第一个参数然后输入第二个参数并得到结果。我写了代码,但它没有显示正确的地址。答案显示了我所期望的不同结果。倍数和除法给出了正确的结果,但加法和减去错误。请帮忙。

#include<iostream>
using namespace std;
int main()
{
    int a = 1, b = 2, c = 3, d = 4;
    int first_argument, second_argument;

    cout << "Please choose the number: " <<endl<< "1.Multiple"<<endl<<"2.Divide"  <<endl<<"3.Substract"<<endl<<"4.Add" << "\n";
    cin >> a,b,c,d;
    cout << "Please choose the first argument" << "\n";
    cin >> first_argument;
    cout << "Please choose the second argument" << "\n";
    cin>>second_argument;

    if (a==1)
        cout <<"The answer is "<<first_argument*second_argument<< "\n";
    else if (b == 2)
        cout << "The answer is " << first_argument / second_argument << "\n";
    else if (c == 3)
        cout << "The answer is " << first_argument - second_argument << "\n";
    else if (d == 4)
        cout << "The answer is " << first_argument + second_argument << "\n";



    cin.ignore();
    cin.get();
    return 0;
}

2 个答案:

答案 0 :(得分:2)

cin >> a,b,c,d;

应该是

cin >> a >> b >> c >> d;

否则你调用臭名昭着的comma operator,其lowest precedence,所以你的表达式翻译为

(cin >> a), b, c, d;

只读a然后评估bcd,表达式的最终结果是d,当然不是以后用过。但无论如何,你不需要4个变量来完成这个任务,只有一个就足够了。然后,您需要测试其值,并根据它执行所需的操作。

旁注:分割整数时,结果将被截断。如果您不想要这个,那么将其中一个整数转换为double,例如

first_argument / static_cast<double>(second_argument)

答案 1 :(得分:0)

cin >> a,b,c,d;

没有任何意义。
您很可能只想将用户选择的操作读入单个变量,并在整个if else块中使用该值。

示例:

#include <iostream>
using namespace std;
int main() {
  int operation, first_argument, second_argument;

  cout << "Please choose the number: " << endl << "1.Multiple" << endl << "2.Divide" << endl << "3.Substract" << endl << "4.Add" << "\n";

  cin >> operation;

  cout << "Please choose the first argument"
       << "\n";
  cin >> first_argument;
  cout << "Please choose the second argument"
       << "\n";
  cin >> second_argument;

  if (operation == 1)
    cout << "The answer is " << first_argument * second_argument << "\n";

  else if (operation == 2)
    cout << "The answer is " << first_argument / second_argument << "\n";
  else if (operation == 3)
    cout << "The answer is " << first_argument - second_argument << "\n";
  else if (operation == 4)
    cout << "The answer is " << first_argument + second_argument << "\n";

  cin.ignore();
  cin.get();
  return 0;
}