【C语言做题系列】Doubles

As part of an arithmetic competency program, your students will be given randomly generated lists of from 2 to 15 unique positive integers and asked to determine how many items in each list are twice some other item in the same list. You will need a program to help you with the grading. This program should be able to scan the lists and output the correct answer for each one. For example, given the list
1 4 3 2 9 7 18 22
your program should answer 3, as 2 is twice 1, 4 is twice 2, and 18 is twice 9.
Input
The input file will consist of one or more lists of numbers. There will be one list of numbers per line. Each list will contain from 2 to 15 unique positive integers. No integer will be larger than 99. Each line will be terminated with the integer 0, which is not considered part of the list. A line with the single number -1 will mark the end of the file. The example input below shows 3 separate lists. Some lists may not contain any doubles.
Output
The output will consist of one line per input list, containing a count of the items that are double some other item.
Sample Input
1 4 3 2 9 7 18 22 0
2 4 8 10 0
7 5 11 13 1 3 0
-1
Sample Output
3
2
0

题意:
输入2-15个正整数,找出其中有多少个数是这段数字中其他数的两倍。例如:1 4 3 2 9 7 18 22 你的程序应该回答3,因为2是2乘以1,4是2乘以2,18是2乘以9。
注意:
1,本题要求多组输入,且当输入的第一个数是-1的时候结束输入。
2,当判断是不是其中一个数是其他数的两倍时,切勿重复计数。

上代码:

#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int main()
{
    int i;
    int len;                                 //定义一个变量来存储输入数组的长度
    while(scanf("%d", &a[0])&&a[0]!=EOF)    //多组输入,且当输入的第一个数为-1时结束输入
    {
        len=1;                               //因为已经输入了一个数a[0], 所以此处 赋值1
        for(i=1; i<20; i++)
        {
            scanf("%d", &a[i]);
            len++;
            if(a[i]==0)
                break;
        }
        sort(a,a+len);                      //此处为算法的亮点,把数组的大小排序一遍,后续挨着判断就不会重复计数了
        int j, k;
        int sum=0;
        for(j=0; j<len; j++)                  //从第一个开始,与后面的数进行比较
        {
            for(k=j+1; k<len; k++)
                if(a[j]*2==a[k])
                    sum++;
        }
        printf("%d\n", sum);
    }
    return 0;
}

心得:
上述代码亦可以不用len变量,熟练的话可以直接用i来表示输入数组的长度。

发布了16 篇原创文章 · 获赞 0 · 访问量 454

猜你喜欢

转载自blog.csdn.net/qq_45627679/article/details/104219746