switch语句没有做什么,我期待 [英] Switch statement not doing what I expect

查看:68
本文介绍了switch语句没有做什么,我期待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是错的这个code:

What is wrong with this code:

switch (n)
{
    case 0:   strcpy(resultString, "Zero");
    case 1:   strcpy(resultString, "One");
    case 2:   strcpy(resultString, "Two");
    case 3:   strcpy(resultString, "Three");
    case 4:   strcpy(resultString, "Four");
    case 5:   strcpy(resultString, "Five");
    case 6:   strcpy(resultString, "Six");
    case 7:   strcpy(resultString, "Seven");
    case 8:   strcpy(resultString, "Eight");
    case 9:   strcpy(resultString, "Nine");
}
printf("%s", resultString);

它总是打印九的n无论价值。我在做什么错了?

It always prints "Nine" no matter the value of n. What am I doing wrong??

推荐答案

您需要每个案件的最后一个break语句。否则,控制下降直接传送到下一个案例。

You need a break statement at the end of each case. Otherwise control falls straight through to the next case.

更改code为:

switch (n)
{
    case 0: strcpy(resultString, "Zero"); 
            break;
    case 1: strcpy(resultString, "One"); 
            break;
    case 2: strcpy(resultString, "Two"); 
            break;
    case 3: strcpy(resultString, "Three"); 
            break;
    case 4: strcpy(resultString, "Four"); 
            break;
    case 5: strcpy(resultString, "Five"); 
            break;
    case 6: strcpy(resultString, "Six"); 
            break;
    case 7: strcpy(resultString, "Seven"); 
            break;
    case 8: strcpy(resultString, "Eight"); 
            break;
    case 9: strcpy(resultString, "Nine"); 
            break;
}
printf("%s", resultString);

您可以找到switch语句记录或任何一本书的C语言href=\"http://msdn.microsoft.com/en-us/library/66k51h7a.aspx\">。

You can find the switch statement documented here or in any book on the C language.

这篇关于switch语句没有做什么,我期待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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