Chinaunix首页 | 论坛 | 博客
  • 博客访问: 36663
  • 博文数量: 18
  • 博客积分: 392
  • 博客等级: 一等列兵
  • 技术积分: 210
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-22 18:10
文章分类
文章存档

2011年(18)

我的朋友
最近访客

分类: C/C++

2011-02-26 04:22:57

14、输入4个整数,要求按由小到大的顺序输出。
  1. #include<iostream>
  2. #define NUMBER 4
  3. using namespace std;
  4. void sort(int *num)
  5. {
  6.  int i, j;
  7.  for(i=0; i<NUMBER-1; i++) {
  8.   for(j=i; j<NUMBER; j++) {
  9.    if(num[i] > num[j]) {
  10.     int t = num[i];
  11.     num[i] = num[j];
  12.     num[j] = t;
  13.    }
  14.   }
  15.  }
  16. }

  17. int main()
  18. {
  19.  int num[NUMBER];
  20.  int i;
  21.  cout << "Input 4 number : ";
  22.  for(i=0; i<NUMBER; i++)
  23.   cin >> num[i];
  24.  sort(num);
  25.  for(i=0; i<NUMBER; i++)
  26.   cout << num[i] << " ";
  27.  cout << endl;
  28.  return 0;
  29. }
15、输入两个正整数m和n,求其最大的公约数和最小公倍数。
  1. #include <iostream>
  2. int main()
  3. {
  4. int m, n;
  5. int m_cup, n_cup, res; /*被除数, 除数, 余数*/
  6. printf("Enter two integer:\n");
  7. scanf("%d %d", &m, &n);
  8. if (m > 0 && n >0)
  9. {
  10. m_cup = m;
  11. n_cup = n;
  12. res = m_cup % n_cup;
  13. while (res != 0)
  14. {
  15. m_cup = n_cup;
  16. n_cup = res;
  17. res = m_cup % n_cup;
  18. }
  19. printf("Greatest common divisor: %d\n", n_cup);
  20. printf("Lease common multiple : %d\n", m * n / n_cup);
  21. }
  22. else printf("Error!\n");
  23. return 0;
  24. }
19、输出所有的“水仙花数”,所谓水仙花数是指一个三位数,其各位数字的立方之和等于该数本身。
  1. #include<iostream>
  2. #include<cmath>
  3. using namespace std;
  4. void getArmstrongNumber(int n1, int n2);
  5. int main()
  6. {
  7.  getArmstrongNumber(25,99999);
  8.  return 0;
  9. }
  10. void getArmstrongNumber(int n1, int n2)
  11. {
  12.  int x,n;//x是n位数

  13.  for(x=n1;x<=n2;x++)
  14.  {
  15.   int temp=x,s=0;
  16.   n=0;
  17.   while(temp!=0)//计算数位n

  18.   {
  19.    n++;
  20.    temp/=10;
  21.   }
  22.   temp=x;
  23.   while(temp!=0)
  24.   {
  25.    s+=pow((temp%10),n);
  26.    temp/=10;
  27.   }
  28.   if(s==x)
  29.    cout<<x<<"是水仙花数!"<<endl;
  30.  }
  31. }
20、一个数如果恰好等于它的因子之和,这个数就称为“完数”。编程找出1000之内的所有完数,并按下面的格式输出其因子:
6 是一个完数,其因子有1,
2,
3
  1. #include<iostream.h>
  2. void main()
  3. {
  4.  int i,j,sum=0;
  5.  for(i=1;i<=1000;i++)
  6.  {
  7.   sum=0;
  8.   for(j=1;j<i;j++)
  9.   {
  10.    if(i%j==0)
  11.     sum+=j;
  12.   }
  13.   if(sum==i)
  14.   {
  15.    cout<<i<<" 是一个完数,其因数有 ";
  16.    for(j=1;j<i;j++)
  17.    {
  18.     if(i%j==0)
  19.      cout<<j<<","<<endl;
  20.    }
  21.   }
  22.  }
  23. }
上面都是百度上找的答案,看了代码才知道算法真的很重要,思考问题的方向和处理问题的方式都很重要,原来编程比的就是算法啊。一定要加油仔细的领会上面处理问题的思路和方法了。。。。。
阅读(802) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~