两倍问题 nefu08

版权声明:沉迷代码,难以自拔 https://blog.csdn.net/qq_33846054/article/details/50585233
description 
给定2到15个不同的正整数,你的任务是计算这些数里面有多少个数对满足:数对中一个数是另一个数的两倍。比如给定1 4 3 2 9 7 18 22,得到的答案是3,因为2是1的两倍,4是2个两倍,18是9的两倍。 
 
input 
输入包括n组测试数据。每组数据包括一行,给出2到15个两两不同且小于100的正整数。每一行最后一个数是0,表示这一行的结束后,这个数不属于那2到15个给定的正整数。
 
output 
对每组输入数据,输出一行,给出有多少个数对满足其中一个数是另一个数的两倍。
 
sample_input 
3
1 4 3 2 9 7 18 22 0
2 4 8 10 0
7 5 11 13 1 3 0
 
sample_output 
3
2
0
 

经过苦苦思索的结果,发现并没有想象中那么的难~好高兴

#include <iostream>
#include <math.h>
#include <stdio.h>
#include <algorithm>
using namespace std;

int main()
{
    int n,a[15],i,j,k,count;
    cin>>n;
    while (n--)
    {
        i=count=0;
        while (1)
        {
          cin>>a[i];
          if (a[i]==0)
          break;
          i++;
        }
        k=i;
        sort(a,a+k);
        for (i=0;i<k;i++)
        {for (j=i;j<k;j++)
            if (a[j]==2*a[i])
            count++;}


cout << count<< endl;

    }




    return 0;
}

  1. 输入未知数量的数据进入数组,以0为结尾,并且统计数字的数量;
i=0;
while (1)
        {
          cin>>a[i];
          if (a[i]==0)
          break;
          i++;
        }
        k=i;

2.两倍的问题
sort(data,data+k)进行升序排序;、
然后类比选择排序的方法分别寻找出二倍的数据。

猜你喜欢

转载自blog.csdn.net/qq_33846054/article/details/50585233