21xrx.com
2024-09-20 00:00:24 Friday
登录
文章检索 我的文章 写文章
C++ 循环练习题目集
2023-07-08 16:49:59 深夜i     --     --
C++语言 循环 练习题 循环控制语句 编程练习

C++是一种广泛使用的编程语言,在计算机科学领域有着重要的地位。对于C++的初学者来说,掌握循环语句是非常重要的一步。

下面是一些C++循环练习题目,帮助初学者巩固和加强他们的基础。

1. 编写一个程序,使用for循环输出从1到100之间的所有偶数。


for (int i = 2; i <= 100; i += 2)

  cout << i << endl;

2. 编写一个程序,使用while循环计算1到10之间的所有数字的阶乘。


int i = 1;

int factorial = 1;

while (i <= 10) {

  factorial *= i;

  i++;

}

cout << factorial << endl;

3. 编写一个程序,使用do while循环猜数字游戏。程序生成一个1到100之间的随机数字,然后提示用户去猜测数字,直到猜中为止。程序应该告诉用户,用户的猜测是太大还是太小。


#include <cstdlib>

#include <ctime>

int main() {

  srand(time(NULL));

  int randomNumber = rand() % 100 + 1;

  int guess;

  do {

    cout << "Guess the number (1-100): ";

    cin >> guess;

    if (guess > randomNumber)

      cout << "Too high!" << endl;

     else if (guess < randomNumber)

      cout << "Too low!" << endl;

    

  } while (guess != randomNumber);

  cout << "You guessed it!" << endl;

  return 0;

}

4. 编写一个程序,使用双重循环输出一个九九乘法表。


for (int i = 1; i <= 9; i++) {

  for (int j = 1; j <= 9; j++) {

    cout << i << " * " << j << " = " << i * j << endl;

  }

}

5. 编写一个程序,使用嵌套循环输出以下图形。


*

**

***

****

*****

for (int i = 1; i <= 5; i++) {

  for (int j = 1; j <= i; j++) {

    cout << "*";

  }

  cout << endl;

}

这些C++循环练习题目可能看起来简单,但对于初学者来说,这是一个很好的起点,以帮助他们更好地理解循环语句。通过练习,他们可以巩固和加强他们的基础,为更高级的编程挑战做好准备。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复