21xrx.com
2025-06-12 15:21:40 Thursday
文章检索 我的文章 写文章
"C++互动乐趣:简单有趣的编程代码"
2023-07-06 05:46:15 深夜i     --     --
C++ 互动 乐趣 简单 编程代码

C++是一种聚焦于性能和速度的编程语言。虽然它通常用于编写大型,高度功能的应用程序和操作系统,但也可以用来创建简单和有趣的互动应用程序。

以下是几个简单而有趣的C++编程代码,这些代码可以让你通过编程与计算机进行互动。

1. 猜数游戏

这是一个C++猜数字游戏。它要求用户在1到100之间猜数字,然后告诉他们他们猜得是否正确,并给他们提示他们应该猜高或低。

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
  srand(time(0));    // 用当前时间设置种子
  int secretNumber = rand() % 100 + 1// 生成1到100之间的随机数字
  int guess;
  int tries = 0;
  do {
    cout << "Enter a guess: ";
    cin >> guess;
    tries++;
    if(guess > secretNumber)
      cout << "Too high!" << endl;
     else if(guess < secretNumber)
      cout << "Too low!" << endl;
     else
      cout << "You guessed it in " << tries << " tries!" << endl;
    
  } while(guess != secretNumber);
  return 0;
}

2. 打印乘法表

这是一个打印乘法表的C++程序。它要求用户输入想要打印的表的大小,然后打印该大小的乘法表。

#include <iostream>
using namespace std;
int main()
{
  int size;
  cout << "Enter the size of the multiplication table: ";
  cin >> size;
  for(int i=1; i<=size; ++i) {
    for(int j=1; j<=size; ++j) {
      cout << i * j << "\t";
    }
    cout << endl;
  }
  return 0;
}

3. 简单的计算器

这是一个C++计算器程序。它要求用户输入两个数字和运算符,然后计算结果。

#include <iostream>
using namespace std;
int main()
{
  float num1, num2, result;
  char op;
  cout << "Enter the first number: ";
  cin >> num1;
  cout << "Enter the second number: ";
  cin >> num2;
  cout << "Enter the operator (+, -, *, /): ";
  cin >> op;
  switch(op) {
    case '+':
      result = num1 + num2;
      break;
    case '-':
      result = num1 - num2;
      break;
    case '*':
      result = num1 * num2;
      break;
    case '/':
      result = num1 / num2;
      break;
    default:
      cout << "Invalid operator!" << endl;
      return 1;
  }
  cout << "Result: " << result << endl;
  return 0;
}

这些简单的代码可以让你开始使用C++在编程领域进行互动。无论你是初学者还是有经验的程序员,这些代码都能为你的学习和创造活动提供有趣而有意义的体验。

  
  

评论区