21xrx.com
2025-06-19 01:57:34 Thursday
文章检索 我的文章 写文章
C++ if语句练习题
2023-07-01 21:16:17 深夜i     24     0
C++ if语句 练习题 条件语句 控制流程

C++语言是一种面向对象的程序设计语言,它已经成为安卓、游戏、嵌入式、金融、通信等领域最为流行的编程语言之一。在C++的学习过程中,if语句是必不可少的内容。今天我们来看几个if语句的练习题,来提高我们对if语句的掌握和理解。

1. 小于10的数平方,大于10的数输出“Hello World”

这是一个非常基本的if语句练习题,它可以让我们掌握if语句的基本语法和运用方法。下面是实现代码:

#include <iostream>
using namespace std;
int main()
{
  int x;
  cin >> x;
  if (x < 10)
    cout << x * x << endl;
  else
    cout << "Hello World" << endl;
  return 0;
}

2. 找出两个数中的最大值

这是另一个基本的if语句练习题,它可以帮助我们加深对if语句的理解。下面是实现代码:

#include <iostream>
using namespace std;
int main()
{
  int num1, num2;
  cin >> num1 >> num2;
  if (num1 > num2)
    cout << num1 << endl;
  else
    cout << num2 << endl;
  return 0;
}

3. 手速小游戏

这是一个有趣的if语句练习题,它可以让我们进一步理解if语句的特点。下面是实现代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
  srand((int)time(0));
  int num1 = rand() % 10;
  int num2;
  cout << "请输入" << num1 << "加上5的数:";
  cin >> num2;
  if (num2 == num1 + 5)
    cout << "你回答正确!" << endl;
  else
    cout << "你回答错误!" << endl;
  return 0;
}

这些练习题虽然看起来简单,但却可以让我们不断掌握if语句的特点和使用方法,所以我们必须认真对待这些练习题,并在实际中不断地练习和运用。

  
  

评论区