将Integer拆分为两个单独的Integer [英] Split Integer into two separate Integers
问题描述
假设我有
int n=123456;
int x,y=0;
如何拆分整数"n"?分两半.
How do I split the integer "n" in two half.
注意: n
中的总位数始终是2的倍数,例如 1234、4567、234567、345621等...都具有2,4,6,8位数字.我想将它们分成两半.
Note : The Total Number of digits in n
will always be multiple of 2, e.g. 1234, 4567, 234567, 345621 etc... all have 2,4,6,8 digits.
I want to divide them in half.
我正在尝试使用以下代码,但无法正常工作, y
变量以某种方式保留了相反的第二部分.
I am trying with following Code but it's not working, the y
variable is holding reversed second part somehow.
int x, y=0, len, digit;
int n=123456;
len=floor(log10(abs(n))) + 1;
x=n;
while((floor(log10(abs(x))) + 1)>len/2)
{
digit=x%10;
x=x/10;
y=(y*10)+digit;
}
printf("First Half = %d",x);
printf("\nSecond Half = %d",y);
当输入为时:
n = 123456;
n=123456;
我得到的输出:
上半场= 123
下半场= 654
First Half = 123
Second Half = 654
我想要的输出:
上半场:123
First Half : 123
下半场:456
推荐答案
这是一个演示程序.除了printf之外,它不使用任何功能.:)因此,这是最简单的解决方案.
Here is a demonstrative program. It does not use any function except printf.:) Thus it is the simplest solution.
#include <stdio.h>
int main( void )
{
unsigned int a[] = { 12, 1234, 123456, 12345678, 1234567890 };
const unsigned int Base = 10;
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
unsigned int divisor = Base;
while ( a[i] / divisor > divisor ) divisor *= Base;
printf( "%u\t%u\n", a[i] / divisor, a[i] % divisor );
}
}
程序输出为
1 2
12 34
123 456
1234 5678
12345 67890
如果您要使用带符号的整数类型和负数,则程序可以采用以下方式
If you are going to use a signed integer type and negative numbers then the program can look the following way
#include <stdio.h>
int main( void )
{
int a[] = { -12, 1234, -123456, 12345678, -1234567890 };
const int Base = 10;
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
int divisor = Base;
while ( a[i] / ( a[i] < 0 ? -divisor : divisor ) > divisor ) divisor *= Base;
printf( "%d\t%d\n", a[i] / divisor, a[i] % divisor );
}
}
其输出为
-1 -2
12 34
-123 -456
1234 5678
-12345 -67890
这篇关于将Integer拆分为两个单独的Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!