Larger than and less than in C switch statement

后端 未结 7 859
闹比i
闹比i 2020-12-29 04:57

I\'m trying to write a code that has a lot of comparison

Write a program in “QUANT.C” which “quantifies” numbers. Read an integer “x” and test it, pro

7条回答
  •  不知归路
    2020-12-29 05:32

    If you are using gcc, you have "luck" because it supports exactly what you want by using a language extension:

    #include 
    ...
    
    switch(a)
    {
    case 1000 ... INT_MAX: // note: cannot omit the space between 1000 and ...
        printf("hugely positive");
       break;
    case 100 ... 999:
        printf("very positive");
       break;
    ...
    }
    

    This is non-standard though, and other compilers will not understand your code. It's often mentioned that you should write your programs only using standard features ("portability").

    So consider using the "streamlined" if-elseif-else construct:

    if (a >= 1000)
    {
        printf("hugely positive");
    }
    else if (a >= 100)
    {
        printf("very positive");
    }
    else if ...
    ...
    else // might put a helpful comment here, like "a <= -1000"
    {
        printf("hugely negative");
    }
    

提交回复
热议问题