简体   繁体   English

将一个9位数转换为三个3位数

[英]Converting a 9 digit number into three 3 digit number

Ok everyone so i have a 9 digit number in input ( 123456789 ) and i need to break it down to first middle and last three numbers ( 123,456,789 ). 好的,大家好,我在输入中有9位数字( 123456789 ),我需要将其分解为第一个中位数和最后三个数字( 123,456,789 )。 I know that i can use modulo to get the last three digits. 我知道我可以使用取模来获取最后三位数字。

first_group_of_three = input number % 1000;

But i have no idea how to get the other two groups. 但是我不知道如何获得另外两个小组。 Any help would be appreciated. 任何帮助,将不胜感激。

UPDATE ! 更新! Thanks to milevyo answer i managed to figure it out.Now for the code freaks out there,i am a beginner programmer and i would like to ask what is a more efficient way to write this code(below),maybe using less variables or some other technique.I didn't transform it to char because we are not allowed to since we still "havent learned it" 多亏了milevyo的回答,我设法弄清楚了。现在因为代码很怪异,我是一个初学者,我想问一下(下面)编写这种代码的更有效的方法是什么,也许使用更少的变量或一些其他技术。我没有将其转换为char,因为我们仍然“已经学会了它”,因此我们被禁止这样做

     scanf("%d" , &input_number);
   last_group_of_three = input_number % 1000;
   temp = (input_number-last_group_of_three)/1000;
   middle_group_of_three = temp % 1000;
   first_group_of_three = (temp-middle_group_of_three)/1000;
first_group_of_three = input number % 1000;
shift=(input number-first_group_of_three)/1000

second_group_of_three = shift % 1000;

and so on

Simplification: @Barmar 简化: @Barmar

scanf("%d", &input_number);

last_group_of_three = input_number % 1000;
input_number /= 1000;

middle_group_of_three = input_number % 1000;
input_number /= 1000;

// % 1000 only if original input exceeded 9 digits
first_group_of_three = input_number % 1000; 

Note: many compilers will optimize the % 1000 and / 1000 into a single operation providing the two results: remainder & quotient. 注意:许多编译器会将% 1000/ 1000优化为一个操作,提供两个结果:余数和商。

(OP has not mention what code should do with negative numbers.) (OP没有提到负数应该用什么代码。)

您可以在char表中以字符串形式输入数字,然后前3个数字将保留在表的第4个char中,成为char',',第5、6、7th个char将是下3个数字,以此类推。最后创建字符串“ 123,456,789”,然后打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM