为什么开关中的情况3没有执行? [英] Why case 3 in a switch not executing ?

查看:75
本文介绍了为什么开关中的情况3没有执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[#include <stdio.h>
#include <stdlib.h>
#define MEAN(a,b) (float)(a+b)/2
#define ABS(n) (n>0?n:n*-1)
#define TOLOWER(x) (x+32)
int main()
{

    int i,a,b,j;
    char k;
    printf("Enter 1 for MEAN\n2 for ABS\n3 for TOLOWER\n");
    scanf("%d",&i);
    switch(i)
    {
        case 1: printf("Enter a nd b\n");
                scanf("%d %d",&a,&b);
                printf("%f\n",MEAN(a,b));
                break;
        case 2: printf("Enter a no to find abs\n");
                scanf("%d",&j);
                printf("%d\n",ABS(j));
                break;
        case 3: printf("Enter upper to lower\n");
                scanf("%c",&k);
                printf("%c\n",TOLOWER(k));
                break;
        default: printf("Hey wat u dng ? Its a wrong input\n");
                break;
    }
    return 0;
}
]





我尝试了什么:



没有Switch case声明我可以轻松执行,但为什么不能使用switch case?

自动输入第3个案例*即将来临。为什么这样 ?我正在使用代码块。



What I have tried:

Without Switch case Statement I can execute easily, but why not with switch case ?
on entering 3rd case automatically character * is coming. Why So ? I am using code blocks.

推荐答案

可能是因为您正在从输入中读取单个字符,而这是您输入的3中的剩余:

Probably because you are reading a single character from the input, and it's the "leftovers" from the '3' you entered:
case 3: printf("Enter upper to lower\n");
        scanf("%c",&k);
        printf("%c\n",TOLOWER(k));

你想要做的就是阅读一串字符并选择第一个字母字符。



加:如果用户输入'g'而不是'G'会发生什么?你的TOLOWER宏工作吗?

Probably what you want to do is read a string of characters and select the first one that is alphabetic.

Plus: what happens if the user enters 'g' instead of 'G'? Does your TOLOWER macro work?


#include <stdio.h>
#include <stdlib.h>
#define MEAN(a,b) (float)(a+b)/2#define ABS(n) (n>0?n:n*-1)
#define TOLOWER(x) (x+32)
int main()
{

    int i,a,b,j;
    char k;
    printf("Enter 1 for MEAN\n2 for ABS\n3 for TOLOWER\n");
    scanf("%d",&i);
    switch(i)
    {
        case 1: printf("Enter a nd b\n");
                scanf("%d %d",&a,&b);
                printf("%f\n",MEAN(a,b));
                break;
        case 2: printf("Enter a no to find abs\n");
                scanf("%d",&j);
                printf("%d\n",ABS(j));
                break;
        case 3: printf("Enter upper to lower\n");

                scanf("\n%c",&k);      //add a new line here '\n'

                printf("%c", TOLOWER(k));
                break;
        default: printf("Hey wat u dng ? Its a wrong input\n");
                break;
    }
    return 0;
}


这篇关于为什么开关中的情况3没有执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆