栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

零基础学习C++(4.2)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

零基础学习C++(4.2)

4.2 循环结构

语法: while(循环条件){循环语句}

#include
using namespace std;

int main(){

int num = 0;
cout << num << endl;

while(num < 10)
{
num++;
cout << num << endl;
}

system("pause");
return 0;

}

while循环练习案例:猜数字

案例描述:系统随机生成一个1到100之间的数字,玩家进行猜测,如果猜错,提示玩家过大或过小,如果猜对恭喜玩家胜利,并且退出游戏。

#include
using namespace std;
//time系统时间头文件包含
#include

int main(){

//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样
srand((unsigned int)time(NULL));

int num = rand()%100+1//rand()%100生成0-99随机数
cout << num <> val;


while(1)
{
if(val > num)
{
cout << "猜测过大" << endl;
}
else if(val < num)
{
cout << "猜测过小" << endl;
}
else
{
cout << "恭喜您猜对了" << endl;
break;
}
}

system("pause");
return 0;

}

4.2.2 do...while循环语句

语法:do{循环语句}while{循环条件};

#include
using namespace std;
//time系统时间头文件包含

int main(){

//在屏幕中输出0到9这是个数字
int num = 0;

do
{

cout << num < 

练习案例:水仙花数

案例描述:水仙花数是指一个三位数,它的每个位上的数字的三次幂之和等于它本身

例如:1^3+ 5^3+ 3^3=153

求出所有的水仙花数。

#include
using namespace std;

int main(){

//在屏幕中输出0到9这是个数字
int num = 100;

do
{

int a = 0;
int b = 0;
int c = 0;

a = num % 10;//获取个位
b = num / 10 % 10;//获取十位
c = num / 100 % 10;//获取百位
if(a*a*a+b*b*b+c*c*c == num)
{
cout << num < 

 4.2.3 for循环语句

语法:for{起始表达式;条件表达式;末尾循环体}{ 循环语句 }

#include
using namespace std;

int main(){

//从数字0打印到9

for( int i = 0; i < 10; i++ )
{
  cout << i << endl;
}

system("pause");
return 0;

}

 练习案例:敲桌子

案例描述:从1开始数到数字100,如果数字个位含有7,或该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。

#include
using namespace std;

int main(){

for( int i = 1; i <= 100; i++ )
{
  if ( i % 7 == 0 || i % 10 == 7 || i / 10 == 7 )
{
  cout << "敲桌子" << endl;
}
   cout << i << endl;
}

system("pause");
return 0;

}

 4.2.4 嵌套循环

#include
using namespace std;

int main(){
//利用嵌套循环实现星图

for( int i = 0; i < 10; i++ )
{
 for( int j = 0; j < 10; j++ )
 {
   cout << "* ";
 }
 cout << endl
}

system("pause");
return 0;

}

乘法口诀表 

#include
using namespace std;

int main(){
//乘法口诀表

for( int i = 1; i <= 9; i++ )
{
 cout << j << endl;
 for( int j = 1; j < i; j++ )
 {
   cout << j << " * " << i << " ";
 }
 cout << endl
}

system("pause");
return 0;

}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/766800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号