C:如何将多位数分解为单独的变量?
假设我在 C 中有一个多位整数。我想将它分解为一位数整数。
123
将变成 1
、2
和 3
。
我该如何做到这一点,特别是如果我不知道整数有多少位?
Say I have a multi-digit integer in C. I want to break it up into single-digit integers.
123
would turn into 1
, 2
, and 3
.
How can I do this, especially if I don't know how many digits the integer has?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
首先,计算数字:
然后,您可以将它们存储在数组中:
First, count the digits:
Then, you can store them in an array:
123 的最后一位数字是 123 % 10。
您可以通过执行 123/10 去掉 123 的最后一位数字——使用整数除法,这将得到 12。
回答你关于“我怎么知道你有多少位数字”的问题——
尝试按照上面的描述去做,你就会知道如何知道何时停止。
The last digits of 123 is 123 % 10.
You can drop the last digit of 123 by doing 123/10 -- using integer division this will give you 12.
To answer your question about "how do I know how many digits you have" --
try doing it as described above and you will see how to know when to stop.
提示一下,获取数字中的第 n 位数字非常容易;除以 10 n 次,然后模 10,或者在 C 中:
As a hint, getting the nth digit in the number is pretty easy; divide by 10 n times, then mod 10, or in C:
我认为下面的代码会有帮助......
I think below piece of code will help....
这将导致以下打印输出:
百位 = 9
十位 = 8
单位 = 7
This results in the following printout:
Hundreds = 9
Tens = 8
Units = 7
我根据@asaelr 的代码做了这个:
它工作得很好,谢谢!
I made this based on the code from @asaelr:
It works quite well, thanks!
可以使用%10,表示除以后的余数。所以
123 % 10
是 3,因为余数是 3,用 123 减去 3,就是 120,然后用 10 除 120,就是 12。同样的过程。You can use %10, which means the remainder if the number after you divided it. So
123 % 10
is 3, because the remainder is 3, substract the 3 from 123, then it is 120, then divide 120 with 10 which is 12. And do the same process.我们可以将此程序用作具有 3 个参数的函数。在“while(a++<2)”中,2 是您需要的位数(可以作为一个参数给出)将 2 替换为您需要的位数。如果我们不需要最后的某些数字,我们可以使用“z/=pow(10,6)”,将 6 替换为不需要的数字(可以作为另一个参数给出),第三个参数是您需要打破的数字。
we can use this program as a function with 3 arguments.Here in "while(a++<2)", 2 is the number of digits you need(can give as one argument)replace 2 with no of digits you need. Here we can use "z/=pow(10,6)" if we don't need last certain digits ,replace 6 by the no of digits you don't need(can give as another argument),and the third argument is the number you need to break.
你可以分而治之,但你已经重写了所有的算术库。我建议使用多精度库 https://gmplib.org 但这当然是一个很好的做法
You can divide and conquer but you have rewrite all of arithmetic libraries. I suggest using a multi-precision library https://gmplib.org But of course it is good practice