如何在c中将10位数字分成两个5位数字?
how to break 10 digit number into two 5 digit number in c?
假设我有 char[10]="1234567890
。我希望它用两个 5 位数来打破它。我想问两件事,我需要在拆分之前将它转换为 int 以及我将如何拆分它
首先请注意,您应该编写 char arr[11]="1234567890"
,或者更好的是 char arr[]="1234567890"
,因为您需要为包含字符串文字的空终止符提供 space。如果您不提供,编译器将计算出正确的大小。
但是有一种数字方式可以实现你想要的,这比使用字符串更有效。
以数字开头或将字符串转换为 uint64_t
,称其为 x。您需要一个 64 位整数,因为某些 10 位数字对于 32 位整数来说太大了。
计算 x / 100000。这是比较重要的部分。
计算 x % 100000。这是最不重要的部分。
如果您的问题有 char arr[10] = "1234567890"
,请注意它不是字符串,因为它没有空间容纳 NUL 终止符(需要大小 11
,或者留空 []
让编译器为你计算)。假设您想要其中的两个字符串,则需要将两半复制到单独的数组中,例如:
char topHalf[6], bottomHalf[6]; // 6 = 5 + NUL
(void) memcpy(topHalf, arr, 5); // copy 5 chars from beginning of arr
(void) memcpy(bottomHalf, arr + 5, 5); // arr + 5 to skip the 5 in topHalf
topHalf[5] = '[=10=]'; // terminate string
bottomHalf[5] = '[=10=]'; // "
前
char num10[]="1234567890";
int n1, n2;
sscanf(num10, "%5d%5d", &n1, &n2);
printf("%d, %d\n", n1, n2);
你是指下面的意思吗?
#include <stdio.h>
int main( void )
{
char number[10] = "1234567890";
const size_t N = sizeof( number ) / sizeof( *number );
int num1 = 0, num2 = 0;
int *p = &num1;
for ( size_t i = 0; i < N; i++ )
{
if ( i == ( N + 1 ) / 2 ) p = &num2;
*p = *p * 10 + number[i] - '0';
}
printf( "num1 = %d, num2 = %d\n", num1, num2 );
}
程序输出为
num1 = 12345, num2 = 67890
假设我有 char[10]="1234567890
。我希望它用两个 5 位数来打破它。我想问两件事,我需要在拆分之前将它转换为 int 以及我将如何拆分它
首先请注意,您应该编写 char arr[11]="1234567890"
,或者更好的是 char arr[]="1234567890"
,因为您需要为包含字符串文字的空终止符提供 space。如果您不提供,编译器将计算出正确的大小。
但是有一种数字方式可以实现你想要的,这比使用字符串更有效。
以数字开头或将字符串转换为
uint64_t
,称其为 x。您需要一个 64 位整数,因为某些 10 位数字对于 32 位整数来说太大了。计算 x / 100000。这是比较重要的部分。
计算 x % 100000。这是最不重要的部分。
如果您的问题有 char arr[10] = "1234567890"
,请注意它不是字符串,因为它没有空间容纳 NUL 终止符(需要大小 11
,或者留空 []
让编译器为你计算)。假设您想要其中的两个字符串,则需要将两半复制到单独的数组中,例如:
char topHalf[6], bottomHalf[6]; // 6 = 5 + NUL
(void) memcpy(topHalf, arr, 5); // copy 5 chars from beginning of arr
(void) memcpy(bottomHalf, arr + 5, 5); // arr + 5 to skip the 5 in topHalf
topHalf[5] = '[=10=]'; // terminate string
bottomHalf[5] = '[=10=]'; // "
前
char num10[]="1234567890";
int n1, n2;
sscanf(num10, "%5d%5d", &n1, &n2);
printf("%d, %d\n", n1, n2);
你是指下面的意思吗?
#include <stdio.h>
int main( void )
{
char number[10] = "1234567890";
const size_t N = sizeof( number ) / sizeof( *number );
int num1 = 0, num2 = 0;
int *p = &num1;
for ( size_t i = 0; i < N; i++ )
{
if ( i == ( N + 1 ) / 2 ) p = &num2;
*p = *p * 10 + number[i] - '0';
}
printf( "num1 = %d, num2 = %d\n", num1, num2 );
}
程序输出为
num1 = 12345, num2 = 67890