21xrx.com
2025-03-31 15:23:19 Monday
文章检索 我的文章 写文章
C++编程:输入两个数并输出加减乘除结果
2023-07-10 00:09:27 深夜i     82     0
C++编程 输入 加减乘除 输出 两个数

C++是一种高级编程语言,被广泛应用于软件开发、游戏开发、嵌入式系统、科学计算、数据处理等领域。在本文中,我们将学习如何使用C++编写一个能输入两个数并输出加减乘除结果的程序。

首先,我们需要定义两个变量,用于存储输入的两个数。在C++中,可以使用int类型来定义整数变量,例如:

int num1, num2;

然后,我们可以通过cin语句来从控制台读取用户输入的数,如下所示:

cout << "请输入两个整数:" << endl;
cin >> num1 >> num2;

接着,我们可以定义四个变量来保存加减乘除结果,以及一个变量来表示运算符。在C++中,运算符可以使用char类型来表示。例如:

int sum, difference, product, quotient;
char oper;

然后,我们可以通过简单的if语句来确定用户输入的运算符类型,并对两个数进行相应的加减乘除运算。例如:

cout << "请输入运算符(+,-,*,/):" << endl;
cin >> oper;
if (oper == '+') {
  sum = num1 + num2;
  cout << "和为:" << sum << endl;
} else if (oper == '-')
  difference = num1 - num2;
  cout << "差为:" << difference << endl;
else if (oper == '*') {
  product = num1 * num2;
  cout << "积为:" << product << endl;
} else if (oper == '/')
  quotient = num1 / num2;
  cout << "商为:" << quotient << endl;
else
  cout << "不支持此运算符" << endl;

最后,我们可以在程序末尾添加以下语句,以保持程序运行并等待用户按下任意键退出,如下所示:

system("pause");
return 0;

完整的C++程序代码如下:

#include <iostream>
using namespace std;
int main() {
  int num1, num2, sum, difference, product, quotient;
  char oper;
  cout << "请输入两个整数:" << endl;
  cin >> num1 >> num2;
  cout << "请输入运算符(+,-,*,/):" << endl;
  cin >> oper;
  if (oper == '+') {
    sum = num1 + num2;
    cout << "和为:" << sum << endl;
  } else if (oper == '-')
    difference = num1 - num2;
    cout << "差为:" << difference << endl;
   else if (oper == '*') {
    product = num1 * num2;
    cout << "积为:" << product << endl;
  } else if (oper == '/')
    quotient = num1 / num2;
    cout << "商为:" << quotient << endl;
   else
    cout << "不支持此运算符" << endl;
  
  system("pause");
  return 0;
}

在以上程序执行后,您可以在控制台中输入两个整数和一个运算符,程序将根据输入进行相应的加减乘除运算,并输出运算结果。这样的程序小巧简便,但支持的运算类型有限,适合初学者学习和练手。如果您想深入学习C++编程,建议参考更多高级的C++教程和实例,深入理解语法细节和编程思想。

  
  

评论区

请求出错了