在c中使用switch语句时遇到问题 [英] having problems using switch statements in c

查看:123
本文介绍了在c中使用switch语句时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在c中使用switch语句时遇到问题。我正在尝试使这个程序取一个数字并将其写出来,例如98变成九八。当我运行我的程序但是我只得到零。

任何帮助表示赞赏,谢谢。



Hello, I am having a problem using switch statements in c. I am trying to make this program to take a number and write it out it letters for example 98 turns into nine eight. When i run my program however i only get zero.
Any help is appreciated, thanks.

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

printf("insert number: ");
scanf("%d",&x);
switch (x)
{
        case 1:
        printf("one");
        break;

        case 2:
        printf("two");
        break;

        case 3:
        printf("three");
        break;

        case 4:
        printf("four");
        break;

        case 5:
        printf("five");
        break;

        case 6:
        printf("six");
        break;

        case 7:
        printf("seven");
        break;

        case 8:
        printf("eight");
        break;

        case 9:
        printf("nine");
        break;

        default:
        printf("zero");
        break;
}
}

推荐答案

嗯...如果你输入的话,你会得到一个非零值单个数字!

但是如果输入的值大于或等于10,则它将与您显示的任何显式值都不匹配,因此默认值将使用价值。



如果您想将98转换为九八,那么您需要将输入数字作为单独的数字处理 - 从最大的第一个开始 - 并为每个人执行开关块。

首先移动开关进入一个函数,它接受一个整数并返回一个const char指针然后你可以处理数字。



获得最低位数很容易:

Well...you will get a non-zero value if you enter just a single digit!
But if you enter a value greater than or equal to ten, it won't match any of the explicit values you show so the default value will be used.

If you want to convert "98" into "nine eight", then you need to process the input number as separate digits - working from the largest first - and do the switch block for each of them.
So start by moving the switch into a function which takes an integer and returns a const char pointer and then you can work on the digits.

Getting the lowest digit is easy:
digit = value % 10;

会做得很好。并且以最低的第一顺序处理所有数字的循环也非常简单。但是你能先弄清楚如何最先处理它们吗?试一试......

will do it nicely. And a loop to work on all digits in lowest first order is also pretty simple. But can you work out how to process them highest first? Give it a try...


这篇关于在c中使用switch语句时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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