C++ do while练习题
时间: 2024-08-13 15:08:17 浏览: 177
C++中的do-while循环是一种条件执行循环,它会先执行循环体一次,然后再检查条件是否为真。如果条件为真,就会继续执行循环;如果条件为假,则跳出循环。以下是一些关于do-while循环的练习题示例:
1. **基本do-while循环**:
编写一个程序,让用户输入一个数字,直到输入的是正数为止,然后输出“恭喜你,输入了正数”。
```cpp
#include <iostream>
int main() {
int num;
do {
std::cout << "请输入一个数字(正数):";
std::cin >> num;
} while (num <= 0);
std::cout << "恭喜你,输入了正数: " << num << std::endl;
return 0;
}
```
相关问题
给我出几道c++ do while的练习题
当然可以。`do-while`循环在C++中通常用于至少执行一次循环体,然后根据条件判断是否继续。这里有一些简单的`do-while`循环练习题供你参考:
1. **无限计数器**:
编写一个程序,让用户输入数字,直到用户输入'0'为止。每次循环都要打印当前计数,并询问用户是否还要继续。
```cpp
#include <iostream>
int main() {
int count = 0;
do {
std::cout << "当前计数: " << count << std::endl;
std::cin >> count;
} while (count != 0);
return 0;
}
```
2. **猜数字游戏**:
写一个程序,生成一个随机数,让玩家猜测。如果猜错了,会告诉他们是猜大了还是猜小了,直到猜对为止。`do-while`在这种情况下可以保证至少询问一次。
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0)); // 初始化随机数种子
int secret = rand() % 100 + 1; // 随机数范围从1到100
int guess;
do {
std::cout << "请输入你猜的数字(1-100):";
std::cin >> guess;
} while (guess != secret);
std::cout << "恭喜你,猜对了!" << std::endl;
return 0;
}
```
3. **字符检测**:
创建一个程序,读取用户输入直到遇到换行符,然后显示用户输入了多少次回车和空格。
```cpp
#include <iostream>
#include <string>
std::string input;
int enter_count = 0, space_count = 0;
void processInput() {
if (input.back() == '\n') {
// 如果是换行符,则计算统计值并清空字符串
enter_count++;
input.pop_back();
}
else if (input.back() == ' ') {
space_count++;
input.pop_back();
}
}
int main() {
do {
std::getline(std::cin, input);
} while (!input.empty());
std::cout << "换行次数: " << enter_count << ", 空格次数: " << space_count << std::endl;
return 0;
}
```
C++do while循环题目
### C++ Do-While 循环练习题
#### 题目一:计算正整数的位数
编写一个程序,输入任意一个正整数 `n`,使用 do-while 循环来计算并输出该数字的总位数。
```cpp
#include <iostream>
using namespace std;
int main() {
int n, cnt = 0;
cin >> n;
do {
++cnt;
n /= 10;
} while (n != 0);
cout << "位数:" << cnt << endl;
return 0;
}
```
此代码通过不断除以 10 来减少数值大小,并计数直到原数值变为零[^3]。
#### 题目二:猜数字游戏
创建一个简单的猜数字小游戏,在其中玩家需要猜测预设的秘密号码。如果猜测错误,则提示继续尝试;当成功匹配时结束游戏。利用 do-while 实现这一逻辑结构可以确保至少有一次机会让玩家进行猜测。
```cpp
#include <iostream>
using namespace std;
int main() {
const int SECRET_CODE = 789; // 设定秘密码
int guess;
do {
cout << "请输入您的猜测(三位数):";
cin >> guess;
if (guess != SECRET_CODE) {
cout << "很遗憾,您猜错了,请再试一次!" << endl;
}
} while (guess != SECRET_CODE);
cout << "恭喜您找到了正确答案!" << endl;
return 0;
}
```
这段代码展示了如何运用 do-while 结构构建一个简单却有趣的交互式应用程序[^2]。
#### 题目三:打印乘法表
设计一段能够显示指定范围内所有自然数与其对应倍数之间关系表格的应用程序。这里采用双重嵌套形式——外部为 do-while 内部则是标准 for 或者 while ——从而实现更加灵活多变的功能需求。
```cpp
#include <iostream>
using namespace std;
int main(){
int startNum,endNum,i,j;
cout<<"请输入起始范围 :";
cin>>startNum;
cout<<"\n请输入终止范围 :";
cin>>endNum;
i=startNum;
do{
cout<<"\n"<<i<<" 的乘法表:\n";
for(j=1;j<=10;++j){
cout<<i<<" * "<<j<<"="<<i*j<<"\t";
}
i++;
}while(i<=endNum);
return 0;
}
```
上述例子说明了即使是在较为复杂的场景下,do-while 同样能与其他控制流语句良好协作完成特定任务[^1]。
阅读全文
相关推荐
















