C++ 基础复习系列——孙不坚1208
C++ 基础复习系列3(递归算法){Fibonacci函数、Hanoi问题}
三、打印图形类(循环)
利用for循环打印图形只需记住两点 1.记住外层循环列,内层循环行 2.寻找内在循环规律
打印三角形
*
* *
* * *
* * * *
我们会发现这个三角形左边的空格是有规律的,我们把这些空格换成0
000*
00* *
0* * *
* * * *
所以我们可将图形拆解成两部分,一个以3,2,1,0的次序减少输出“0”,一个以1,2,3,4的次序增加输出“*”。
for(int i =1;i<=4;i++)
{
//打印空格
for(int j=1;j<=4-i;j++)
{
cout<<" " ;
}
//打印三角形
for(int m =1;m<=i;m++)
{
cout<<"*";
}
cout<<endl;
}
打印菱形
* 000*
* * 00* *
* * * 0* * *
* * * * = * * * *
* * * 0* * *
* * 00* *
* 000*
//打印上面的上面的三角形
for(int i =1;i <=4;i++){
for(int q=1;q<5-i;q=q+1)
{
cout<<" ";
}
for(int j =1;j<=i;j=j+1)
{
cout<<"*";
}
cout<<endl;
}
//打印下面的倒三角形
for(int i =1;i <=3;i++){
for(int q=1;q<=i;q=q+1)
{
cout<<" ";
}
for(int j =3;j>=i;j=j-1)
{
cout<<"* ";
}
cout<<endl;
}
打印空心菱形
* 000*
* * 00* *
* * 0* 0 *
* * = * 0 0 *
* * 0* 0 *
* * 00* *
* 000*
for(int i =1;i <=4;i++) //打印上半部分三角形
{
for(int q=1;q<5-i;q=q+1)
{
cout<<" ";
}
for(int j =1;j<=i;j=j+1) //分别在第3行的第2个,第4行的第2个,第3个变空格
{
if(i==3&&j==2)
{
cout<<" ";
}
else if(i==4&&j ==2)
{
cout<<" ";
}
else if(i ==4&&j==3)
{
cout<<" ";
}
else
{
cout<<"* ";
}
}
cout<<endl;
//s=s-1;
}
//打印下半部分三角形
for(int i =1;i <=3;i++)
{
for(int q=1;q<=i;q=q+1)
{
cout<<" ";
}
for(int j =3;j>=i;j=j-1)
{//把下半部分三角形的第1行的第2个变空格
if(i==1&&j==2)
{
cout<<" ";
}
else
{
cout<<"* ";
}
}
cout<<endl;
}
四、经典问题类
(1)闰年判断问题
闰年:能被4整除但不能被100整除,或可以被400整除 if(y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
(2)韩信点兵问题
#include<iostream>
using namespace std;
int main()
{
int a=0,b=0,c=0,s=0;
cin>>a>>b>>c;
for(int i=10;i<=100;i++)
{
if(i%3==a&&i%5==b&&i%7==c)
{
cout<<n<<endl;
s=1;
}
}
if(s==0)
{
cout<<"不存在这样的数";
}
return 0;
}
(3)水仙花数问题
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int n;
cin >> n;
while(n)
{
int G,S,B;
B=n/100;
G=n%10;
S=(n%100-ge)/10;
if(pow(G,3)+pow(S,3)+pow(B,3)==n)
cout << "Yes" << endl;
else
cout << "No" << endl;
cin >> n;
}
return 0;
}
(4)数字黑洞问题
详见我另一篇专门关于数字黑洞的博客
(5)经典函数问题
a 判断素数
int prime(int f)
{
int i;
for(i=2;i<f;i++)
if(f%i==0)
return 0;
else
return 1;
}
b 阶乘
long Fac(int n)
{
if (n == 0)
return 1;
else
return n * Fac(n - 1);
}
c 冒泡排序与sort函数排序
详见我另两篇关于冒泡与sort的博客
d 输出0~255的二进制数
#include <iostream>
using namespace std;
int main()
{
for(int a=0;a<2;a++)
{
for(int b=0;b<2;b++)
{
for(int c=0;c<2;c++)
{
for(int d=0;d<2;d++)
{
for(int e=0;e<2;e++)
{
for(int q=0;q<2;q++)
{
for(int s=0;s<2;s++)
{
for(int f=0;f<2;f++)
{
cout<<a<<b<<c<<d<<e<<q<<s<<f<<endl;
}
}
}
}
}
}
}
}
return 0;
}
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset<8>b;
for(int i = 0; i < 256; i++)
{
b = i;
cout<<b<<endl;
}
return 0;
}