切换从输入读取整数的语句并做出相应的反应

时间:2016-05-19 22:54:04

标签: c switch-statement

我有一个小任务给了我,我绝对不知道该做什么。

官方简报是:

"Using switch, create a program that reads an integer from the keyboard and, 
indicate that the number is smaller than 1 and or smaller than 10, and or 
smaller than 100, and or smaller than 1000."

我已尝试首先输入"int num = scanf("%d\n", &num);"

然后执行以下案例

"case (num < 1 && <100): {

    printf("Excellent!!\n" );
    }"

但我没有运气。请有人指出我正确的方向。

谢谢,

编辑:

用这个实验但不知道如何打印它优秀:

#include <stdio.h>
int main () {

int num;
scanf("%d\n", &num);

switch(num) {

case 1:
{
if(num < 1 && num < 10) {

    printf("Excellent!!\n" );
    }
}


}
}

3 个答案:

答案 0 :(得分:2)

int num = scanf("%d\n", &num);

这条线错了。 scanf不会返回刚刚读取的数字;它返回成功读取的元素数。所以把它改成

scanf("%d\n", &num);

至于开关,有效表格是

switch (constant-integral-expression) {
    case one-label:
        actions
        break;
    case another-label:
        actions;
        break;
    default:
        actions if none of the above were satisfied
}

其中default:子句是可选的。例如,如果要计算空格,换行符和制表符:

int c;
int nspace, nnl, ntab;

for (nspace = nnl = ntab = 0; (c = getchar()) != EOF; ) {
    switch (c) {
        case ' ':
            ++nspace;
            break;
        case '\n':
            ++nnl;
            break;
        case '\t':
            ++ntab;
            break;
    }
}
printf("%d %d %d\n", nspace, nnl, ntab);

要写的实际程序,留给读者练习。

编辑:break声明至关重要。如果没有每个break末尾的case语句,控制权就会落到下一个案例中。也就是说,第一种情况之后的案例陈述也将被执行,并且可能产生不希望的影响。

答案 1 :(得分:1)

#include <stdio.h>

int main(void){
    int num;
    int range = 0;

    printf("input num:\n");
    scanf("%d", &num);
    if(num < 1)
        range = -1;
    else {
        while(num /= 10){
            ++range;
        }
    }
    switch(range){
    case -1:
        puts("smaller than 1");
        break;
    case 0:
        puts("smaller than 10");
        break;
    case 1:
        puts("smaller than 100");
        break;
    case 2:
        puts("smaller than 1000");
        break;
    default:
        puts("More than 1000\n");
    }
    return 0;
}

答案 2 :(得分:0)

您可以执行以下操作

#include <stdio.h>

int main( void )
{
    enum { LESS_THAN_1, LESS_THAN_10, LESS_THAN_100, LESS_THAN_1000 };
    int a[] = { 1, 10, 100, 1000 };

    int x;

    printf( "Enter a number: " );

    if ( scanf( "%d", &x ) == 1 )
    {
        int i = 0;
        while ( i < sizeof( a ) / sizeof( *a ) && !( x < a[i] ) ) ++i;

        switch ( i )
        {
        case LESS_THAN_1:
            printf( "x is smaller than %d\n", a[i] );
            break;
        case LESS_THAN_10:
            printf( "x is smaller than %d\n", a[i] );
            break;
        case LESS_THAN_100:
            printf( "x is smaller than %d\n", a[i] );
            break;
        case LESS_THAN_1000:
            printf( "x is smaller than %d\n", a[i] );
            break;
        default:
            printf( "x is greater than or equal to %d\n", a[i-1] );
            break;
        }
    }
}