现在的位置: 首页 > 综合 > 正文

c++练习1

2013年08月30日 ⁄ 综合 ⁄ 共 1170字 ⁄ 字号 评论关闭

 

////题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
#include <iostream>
#include <vector>

//不需要声明这项
//#include <iterator>
using namespace std;
int main()
{
 vector<int> result;//存放满足条件的数
 int num = 0;//满足条件数的个数
 for (int first=1; first<5; first++)
 {
  for (int second=1; second<5; second++)
   if (first != second)
   {
    for (int third=1; third<5; third++)
     if (third != first && third != second)
     {
      int sum = first*100 + second*10 + third;//将百、分、个位的数组成数字
      result.push_back(sum);
      num++;
      cout<<"第"<<num<<"个满足条件的数为"<<sum<<endl;
     }

   }
 }

 cout<<"总共"<<num<<"个满足条件的数"<<endl;

 //下面用两种方法输出vector中的数据,纯属练手
 cout<<"输出容器result,容器大小为"<<result.size()<<endl;

 //方法1
 /*for(size_t i=0; i<result.size(); i++)
  cout<<result.at(i)<<endl;*/

 //方法2
 vector<int>::iterator iter = result.begin();
 vector<int>::iterator last = result.end();
 while (iter != last)
 {
  cout<<*iter<<endl;
  iter++;
 }

 system("pause");
 return 0;

}

 

////答案

1.程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。
2.程序源代码:

//#include <iostream>
//int main()
//{
// int i,j,k;
// printf("\n");
// for(i=1;i<5;i++)
// {
//  for(j=1;j<5;j++)
//  {
//   for (k=1;k<5;k++)
//   {
//    if(i!=k&&i!=j&&j!=k)
//     printf("%d,%d,%d\n",i,j,k);
//
//   }
//
//  }
// }
// system("pause");
// return 0;
//
//}

抱歉!评论已关闭.