[c] double cola

描述:

double cola

Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a “Double Cola” drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on.

For example, Penny drinks the third can of cola and the queue will look like this:

Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny
Write a program that will return the name of the person who will drink the n-th cola.

Input

The input data consist of an array which contains at least 1 name, and single integer n.

1  ≤  n  ≤  10000000000
Output / Examples

Return the single line — the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1.

char* names[] = {“Sheldon”, “Leonard”, “Penny”, “Rajesh”, “Howard”};
who_is_next(names, 5, 1) == “Sheldon”
who_is_next(names, 5, 52) == “Penny”
who_is_next(names, 5, 10010) == “Howard”

代码

#include <stdio.h>
#include <float.h>
#include <math.h>
int main()
{
    //    the types of name
    int length=5;
    //    the number of people
    long long n;
    char *names[]={"Sheldon", "Leonard", "Penny", "Rajesh", "Howard"};
    int  count=0;
    double sum=0 ;
    printf("input n: \n");
    scanf("%lld",&n);
    while(1)
    {
        sum=sum+length;
        if(sum>=n)
        {
//            printf("sum:%lf\n",sum);
            break;}
        length=length*2;
//        printf("length:%d\n",length);
        count=count+1;
    }
    if(length<10)
        sum =0;
    else
        sum=sum-length;
//    printf("*sum:%lf\n",sum);
    count=count+1;
//    printf("count: %d\n",count);
    int time;
    time=pow(2,count-1);
//    printf("time:%d\n",time);
    if(fabs((int)(n-sum)/time-(n-sum)/time)<=FLT_EPSILON)
    {
        printf("%s\n",names[(int)(n-sum)/time-1]);
//        printf("here %lf\n",(n-sum)/time);
        
    }
    else
    {printf("%s\n",names[(int)(n-sum)/time]);
//        printf("there %lf\n",(n-sum)/time);
        
    }
    return 0;
}

发布了51 篇原创文章 · 获赞 5 · 访问量 4216

猜你喜欢

转载自blog.csdn.net/qq_43519498/article/details/86759705