C语言趣味编程100题

1,百钱买百鸡问题

 1 #include <iostream> 
 2 using namespace std;
 3 int main()
 4 {
 5     int x,y,z;
 6     for(int x=0;x<=20;x++)
 7     {
 8         for(int y=0;y<=33;y++)
 9         {
10             for(int z=0;z<=100;z++)
11             {
12                 if(x+y+z==100 && 5*x+3*y+(1.0/3)*z==100)
13                 cout<<x<<" "<<y<<" "<<z<<endl;
14             }
15         }
16         
17     }    
18 }

进一步提高代码效率,确定公鸡和母鸡后,边确定了小鸡,所以只用两层循环便可解决问题。

 1 #include <iostream> 
 2 using namespace std;
 3 int main()
 4 {
 5     int x,y,z;
 6     for(int x=0;x<=20;x++)
 7     {
 8         for(int y=0;y<=33;y++)
 9         {
10             z=100-x-y;
11             if(5*x+y*3+(1.0/3)*z==100)
12             {
13                 cout<<x<<" "<<y<<" "<<z<<endl;
14             }
15         }
16         
17     }    
18 }

借书方案知多少

 1 #include <iostream> 
 2 using namespace std;
 3 int main()
 4 {
 5     int x,y,z,count=0;
 6     for(int x=1;x<=5;x++)
 7     {
 8         for(int y=1;y<=5;y++)
 9         {
10             for(int z=1;z<=5&&x!=y;z++)
11             {
12                 if(y!=z&&x!=z)
13                 {
14                     count++;
15                 }
16             }
17            
18         }
19     }
20     cout<<count<<endl;
21     return 0;
22 }

 

posted @ 2023-05-08 20:57  新晋软工小白  阅读(492)  评论(0)    收藏  举报