21xrx.com
2025-04-01 16:51:31 Tuesday
文章检索 我的文章 写文章
C++上机练习题及解答
2023-07-05 01:16:51 深夜i     9     0
C++ 上机 练习题 解答 编程

C++是一种常用的编程语言,因其语法简洁,代码可读性强,而备受广大程序员的青睐。在学习C++的过程中,通过实战上机练习可以更好地深入理解语言的基本结构和高级特性。下面列举一些实用的C++上机练习题及其详细解答。

1. 计算器程序

要求:用户输入两个数和一个运算符(+,-,*,/),程序输出计算结果。

解答:使用switch语句判断运算符并进行相应的数学运算即可。

#include <iostream>
using namespace std;
int main() {
  float num1, num2, ans;
  char op;
  cout << "Enter two numbers: ";
  cin >> num1 >> num2;
  cout << "Enter an operator (+, -, *, /): ";
  cin >> op;
  switch(op) {
    case '+':
      ans = num1 + num2;
      break;
    case '-':
      ans = num1 - num2;
      break;
    case '*':
      ans = num1 * num2;
      break;
    case '/':
      ans = num1 / num2;
      break;
    default:
      cout << "Invalid operator.";
      return 0;
  }
  cout << num1 << " " << op << " " << num2 << " = " << ans << endl;
  return 0;
}

2. 简单求和程序

要求:用户输入n个数,程序输出这些数的和。

解答:使用for循环依次读入每个数,并累加到sum变量中,最后输出sum的值即可。

#include <iostream>
using namespace std;
int main() {
  int n, sum = 0;
  cout << "Enter the number of integers: ";
  cin >> n;
  for(int i = 1; i <= n; ++i) {
    int x;
    cout << "Enter integer #" << i << ": ";
    cin >> x;
    sum += x;
  }
  cout << "The sum of the integers is " << sum << "." << endl;
  return 0;
}

3. 矩阵乘法程序

要求:用户输入两个矩阵A(m*n)和B(n*p),程序输出它们的乘积C(m*p)。

解答:使用嵌套for循环依次计算C中每个元素的值,公式为C[i][j] = sum(A[i][k] * B[k][j]),其中k为循环变量。需要注意的是,矩阵A和B的大小必须满足乘法规则,即n相等。

#include <iostream>
using namespace std;
int main() {
  int m, n, p;
  cout << "Enter the size of matrix A (m*n): ";
  cin >> m >> n;
  cout << "Enter the size of matrix B (n*p): ";
  cin >> n >> p;
  int A[m][n], B[n][p], C[m][p];
  for(int i = 0; i < m; ++i) {
    for(int j = 0; j < n; ++j) {
      cout << "Enter A[" << i << "][" << j << "]: ";
      cin >> A[i][j];
    }
  }
  for(int i = 0; i < n; ++i) {
    for(int j = 0; j < p; ++j) {
      cout << "Enter B[" << i << "][" << j << "]: ";
      cin >> B[i][j];
    }
  }
  for(int i = 0; i < m; ++i) {
    for(int j = 0; j < p; ++j) {
      int sum = 0;
      for(int k = 0; k < n; ++k) {
        sum += A[i][k] * B[k][j];
      }
      C[i][j] = sum;
    }
  }
  cout << "The product of A and B is:" << endl;
  for(int i = 0; i < m; ++i) {
    for(int j = 0; j < p; ++j) {
      cout << C[i][j] << " ";
    }
    cout << endl;
  }
  return 0;
}

4. 求最大公约数和最小公倍数程序

要求:用户输入两个整数,程序输出它们的最大公约数和最小公倍数。

解答:使用欧几里得算法(辗转相除法)求最大公约数,然后通过乘积除以最大公约数求最小公倍数。

#include <iostream>
using namespace std;
int main() {
  int a, b, gcd, lcm;
  cout << "Enter two integers: ";
  cin >> a >> b;
  int x = a, y = b, r = x % y;
  while(r > 0)
    x = y;
    y = r;
    r = x % y;
  
  gcd = y;
  lcm = a * b / gcd;
  cout << "The greatest common divisor is " << gcd << "." << endl;
  cout << "The least common multiple is " << lcm << "." << endl;
  return 0;
}

通过以上几个C++上机练习题,可以对C++语言的各种基础特性有更深入的认识和理解,是快速提高编程技能和代码质量的有效方法。同时,在学习过程中也应当注重阅读相关文档和书籍,对各种语言特性的背景和使用方法有更深入的认识和了解。

  
  

评论区

请求出错了