1,要求顯示以下圖形987654321
*87654321
**7654321
***654321
****54321
*****4321
******321
*******21
********1
#include <iostream>
using namespace std;
int main()
{
for(int i=0; i<8; i++)
{
for(int j=0; j<i+1; j++)
cout<<"*";
for(int j=8-i; j>0; j--)
cout<<j;
cout<<endl;
}
return 0;
}
運行結果:
2,打印斐波那契數列的前三十個數中所有的質數,並統計個數。
#include <iostream>
using namespace std;
int isPrime(int n) //判斷是否爲素數
{
if(n==1)
return 0;
for(int i=2; i<n; i++)
{
if(n%i==0)
return 0;
}
return 1;
}
int main()
{
int a[50],count=0;
a[0]=1,a[1]=1;
for(int i=2; i<30; i++)
a[i]=a[i-1]+a[i-2];
for(int i=0; i<30; i++)
{
if(isPrime(a[i]))
{
cout<<a[i]<<" ";
count++;
}
}
cout<<endl<<"個數:"<<count<<endl;
return 0;
}
運行結果:
3,袋子裏有2紅3綠5黃球,隨機從中摸出8個,打印顯示所有組合。
#include <stdio.h>
int main()
{
int i,j;
for(i=0; i<=2; i++)
{
for(j=0; j<=3; j++)
{
if(8-i-j<=5)
printf("%d個紅,%d個綠,%d個黃\n",i,j,8-i-j);
else
continue;
}
}
}
運行結果:
5,將十進制ip轉換爲二進制顯示。如輸入128.1.2.128,轉換爲10000000.00000001.00000010.10000000
#include <stdio.h>
void calc(int k) //將k轉化爲二進制
{
int a[8]= {0},i=0,j;
if(k==0)
printf("00000000");
else
{
while(k) //求各位二進制
{
a[i]=k%2;
k=k/2;
i++;
}
i--;
for(j=7; j>=0; j--)
printf("%d",a[j]);
}
}
int main()
{
int a,b,c,d;
char ch1,ch2,ch3;
scanf("%d%c%d%c%d%c%d",&a,&ch1,&b,&ch2,&c,&ch3,&d);//輸入格式如:128.1.2.128
calc(a);
printf("%c",ch1);
calc(b);
printf("%c",ch2);
calc(c);
printf("%c",ch3);
calc(d);
return 0;
}
運行結果: