Larger than and less than in C switch statement

后端 未结 7 789
闹比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:13

    Why do you have a preference to use switch?

    I'm asking because this sounds awfully like a 'homework question'. A compiler should deal with if/else construct just as efficiently as a switch (even if you weren't dealing with ranges).

    Switch can't handle ranges as you have shown, but you could find a way to include switch by categorising the input first (using if/else) then using a switch statement to output the answer.

    0 讨论(0)
  • 2020-12-29 05:18

    use type parameter pattern along with when clause e.g.

    switch(a)
        {
            case * when (a>1000):
                printf("hugely positive");
                break;
            case * when (a>=100 && a<999):
                printf("very positive");
                break;
            case * when (a>=0 && a<100):
                printf("positive");
                break; }
    
    0 讨论(0)
  • 2020-12-29 05:26

    (a>1000) evaluates to either 1 [true] or 0 [false].

    Compile and you will get the error:

    test_15.c:12: error: case label does not reduce to an integer constant
    

    This means, you have to use an integer constant value for the case labels. An If-else if-else loop should work just fine for this case.

    0 讨论(0)
  • 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 <limits.h>
    ...
    
    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");
    }
    
    0 讨论(0)
  • 2020-12-29 05:34

    Use:

    switch (option(a)) {
        case (0): ...
        case (1): ...
        case (2): ...
        case (n): ...
    

    Where the option() function is simply a function with if else.

    It lets you keep the clean look of a switch and the logic part is elsewhere.

    0 讨论(0)
  • 2020-12-29 05:35

    There is no clean way to solve this with switch, as cases need to be integral types. Have a look at if-else if-else.

    0 讨论(0)
提交回复
热议问题