Larger than and less than in C switch statement

后端 未结 7 790
闹比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:36

    A switch-less and if-else-less method:

    #include <stdio.h>
    
    int main(void)
    {
        int a=0, i;
        struct {
            int value;
            const char *description;
        } list[] = {
            { -999, "hugely negative" },
            { -99, "very negative" },
            { 0, "negative" },
            { 1, "zero" },
            { 100, "positive" },
            { 1000, "very positive" },
            { 1001, "hugely positive" }
        };
    
        printf("please enter a number : \n");
        scanf("%i",&a);
    
        for (i=0; i<6 && a>=list[i].value; i++) ;
        printf ("%s\n", list[i].description);
    
        return 0;
    }
    

    The for-loop contains no code (there is just an empty statement ;) but it still runs over the array with values and exits when the entered value a is equal to or larger than the value element in the array. At that point, i holds the index value for the description to print.

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