最小化代码并获得相同的输出

时间:2018-06-12 09:38:32

标签: c

有没有办法缩短这段代码?我的意思是代替写出这么多行;我能写几行并获得相同的输出吗?

#include<stdio.h>
int main()
{
    int input;
    printf("Enter Input \n");
    scanf("%d",&input);

   switch(input)
    {
        case 1: 
            printf("a");
            break;
        case 2: 
            printf("b");
            break;
        case 3: 
            printf("c");
            break;
        case 4: 
            printf("d");
            break;
        case 5: 
            printf("e");
            break;
        case 6: 
            printf("f");
            break;
        case 7: 
            printf("g");
            break;
        case 8: 
            printf("h");
            break;
        case 9: 
            printf("i");
            break;
        case 10: 
            printf("j");
            break;
        default:
            printf("Invalid Input");
    }
    return 0;
}

3 个答案:

答案 0 :(得分:5)

好吧,如果你正在寻找替代品,你可以使用一个阵列。像

这样的东西
 char arr [ ] = "abcdefghij";

然后,你可以这样做

if ( input >= 1 && input <= 10)
    printf("%c", arr[input -1]);
else
    puts ("Invalid");

答案 1 :(得分:1)

我更喜欢不需要额外存储的方式,即阵列。 ASCII是答案的先决条件。小写a的ASCII值为97。

#include <stdio.h>

int main() {
    int input;
    printf("Enter Input \n");
    scanf("%2d",&input);

    if (input <= 10 && input >= 1) {
        printf("%c", 'a' + input - 1);
    } else {
        printf("Invalid Input");
    }
    return 0;
}

enter image description here

答案 2 :(得分:-3)

您可以检查input是否在1到10之间 如果不是,请打印无效的声明
如果是,请打印'a' + ( input - 1 )