[英]Converting a 9 digit number into three 3 digit number
好的,大家好,我在輸入中有9位數字( 123456789
),我需要將其分解為第一個中位數和最后三個數字( 123,456,789
)。 我知道我可以使用取模來獲取最后三位數字。
first_group_of_three = input number % 1000;
但是我不知道如何獲得另外兩個小組。 任何幫助,將不勝感激。
更新! 多虧了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
簡化: @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;
注意:許多編譯器會將% 1000
和/ 1000
優化為一個操作,提供兩個結果:余數和商。
(OP沒有提到負數應該用什么代碼。)
您可以在char表中以字符串形式輸入數字,然后前3個數字將保留在表的第4個char中,成為char',',第5、6、7th個char將是下3個數字,以此類推。最后創建字符串“ 123,456,789”,然后打印。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.