Converting number into word

柔情痞子 提交于 2019-12-02 13:45:49

Try this :

ten_thousand = number/10000;
number = number%10000;

thousand = number/1000;
number = number%1000;

hundred = number/100;
number = number%100;

ten = number/10;
number = number%10;

unit = number;

When you select the units for say thousands, you don't remove the unit before. You forgot the modulo:

thousand=(number % 10000)/1000;

The same is true for all your units, except the first one and the last one, and this is why you only display the first non-zero number and then the last one.

Assume that you want to run your code with 945.

The first calculation would be

945/100 = 9

If you perform number/10 this will lead to:

945/10 = 94

That is why your code does not work. Every time that you divide your "number" you have to scale it.

number = 945
hund = 945/100 = 9
number = number - hund*100 = 45
ten = number/10 = 45/10 ( 4 )
number = number - ten*10 = 5
units = number/1 = 5

Your extraction logic is incorrect, as any good debugger would have revealed to you.

Consider something of the form

unit = number % 10;
number /= 10; // remove the least significant digit by integer division
ten = number % 10;
number /= 10;
hundred = number % 10;
number /= 10;

and so on. This approach is nice as it can be converted to a loop at a later time, with unit, ten, hundred, &c. eventually becoming elements of an array.

Also don't forget to extract any negative sign.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!