我正在尝试自己学习C.我试图将一个整数分成多个单独的整数,例如12345分为12分,34分和5分,但我无法找到办法。
我已经了解了一些Java和编程基础知识。我需要使用某种do-while或for循环来执行此操作,还是可以使用整数数组?
答案 0 :(得分:2)
这可以动态地完成您所需要的!您可以设置所需的任何类型的拆分。 2-2-4或3-4-5或任何东西。 (您基本上可以从用户那里获取一个数字字符串并完成此任务,如果您希望以后将临时字符串转换为整数):
#include <stdio.h>
#include <string.h>
int main() {
int i; //Counter
char getStr[100];
int NumberToSplit1, NumberToSplit2, NumberToSplit3;
printf("Enter a number: ");
scanf("%s", getStr); //get it as a string
//or you can use scanf("%[^\n], getStr);
printf("How many number splits you want: ");
scanf("%d %d %d", &NumberToSplit1, &NumberToSplit2, &NumberToSplit3);
printf("\n%d-%d-%d split: \n", NumberToSplit1, NumberToSplit2, NumberToSplit3);
for (i = 0; i < NumberToSplit1; i++) {
printf("%c", getStr[i]);
}
printf("\n");
for (i = NumberToSplit1; i < (NumberToSplit1+NumberToSplit2); i++) {
printf("%c", getStr[i]);
}
printf("\n");
for (i = (NumberToSplit1+NumberToSplit2); i < (NumberToSplit1+NumberToSplit2+NumberToSplit3); i++) {
printf("%c", getStr[i]);
}
//If you want to save it in an integer, you can use strcat function to save the temp 2 numbers in a string convert that to integer
//or use http://stackoverflow.com/questions/7021725/converting-string-to-integer-c
printf("\n");
printf("\n");
}
输出:
Enter a number: 12345
How many number splits you want: 2 2 4
2-2-4 split:
12
34
5
Program ended with exit code: 0
答案 1 :(得分:1)
否则,首先,将int转换为字符串:
#include <stdio.h>
int n = 12345678;
int len = snprintf(NULL, NULL, "%d", n);
char *digits = malloc(len);
sprintf(digits, "%d", n);
然后你可以用各种方式分割字符串,例如:
int a, b, c;
sscanf(digits, "%2d%2d%4d", &a, &b, &c);
或者:
char sa[2], sb[2], sc[4];
char *cp = digits;
sa[0] = *cp++;
sa[1] = *cp++;
sb[0] = *cp++;
sb[1] = *cp++;
sc[0] = *cp++;
sc[1] = *cp++;
sc[2] = *cp++;
sc[3] = *cp++;
printf("%2c %2c %4c\n", sa, sb, sc);
或者:
// Create 3 buffers to hold null-terminated ('\0' terminated) strings
char sa[3] = { 0 } , sb[3] = { 0 }, sc[4] = { 0 };
char *cp = digits;
sa[0] = *cp++;
sa[1] = *cp++;
sb[0] = *cp++;
sb[1] = *cp++;
sc[0] = *cp++;
sc[1] = *cp++;
sc[2] = *cp++;
sc[3] = *cp++;
printf("%s %s %s\n", sa, sb, sc);
然后释放你的记忆:
free(digits);
...等 等等... 等...
答案 2 :(得分:1)
由于您想要以2-2-4形状分割八位数字,您可以使用整数除法和模数。
假设您不想要负号,如果有的话:
void split( int input, int output[3] )
{
if ( input<0 )
input = -input;
output[0] = input % 10000;
output[1] = ( input / 10000 ) % 100;
output[2] = input / 1000000;
}