aq272776424 2023-12-07 22:17 采纳率: 90%
浏览 7
已结题

大一新生想问一下这个用c语言怎么编?

有一个函数,x和y都为整数,函数关系为:

编写程序,要求键盘输入x的值,输出y的值,分别用:
1) 单if语句实现;
2) if-else语句实现;
3) swtch语句实现

img

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-12-08 08:29
    关注

    【以下回答由 GPT 生成】

    使用单if语句

    #include <stdio.h>
    
    int getYWithIf(int x) {
        if (x >= 0 && x <= 10) {
            return x + 10;
        }
        else {
            return x - 10;
        }
    }
    
    int main() {
        int x;
        printf("Please enter the value of x: ");
        scanf("%d", &x);
    
        int y = getYWithIf(x);
        printf("The value of y is: %d\n", y);
    
        return 0;
    }
    

    使用if-else语句

    #include <stdio.h>
    
    int getYWithIfElse(int x) {
        if (x >= 0 && x <= 10) {
            return x + 10;
        }
        else {
            return x - 10;
        }
    }
    
    int main() {
        int x;
        printf("Please enter the value of x: ");
        scanf("%d", &x);
    
        int y = getYWithIfElse(x);
        printf("The value of y is: %d\n", y);
    
        return 0;
    }
    

    使用switch语句

    #include <stdio.h>
    
    int getYWithSwitch(int x) {
        switch (x) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
                return x + 10;
            default:
                return x - 10;
        }
    }
    
    int main() {
        int x;
        printf("Please enter the value of x: ");
        scanf("%d", &x);
    
        int y = getYWithSwitch(x);
        printf("The value of y is: %d\n", y);
    
        return 0;
    }
    

    请根据需求选择其中一种方式编译并运行代码即可。


    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月29日
  • 已采纳回答 12月21日
  • 创建了问题 12月7日