我正在尝试自学C语言。我试图将一个整数拆分为多个独立的整数,例如12345拆分为12、34和5,但我找不到这样做的方法。
我已经了解了一些Java和编程基础知识。我是否需要使用某种do-while或for循环来完成此操作,或者我是否可以使用整数数组?
发布于 2015-10-05 04:49:43
这就动态地实现了你想要的东西!您可以设置所需的任何拆分类型。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
发布于 2015-10-05 04:34:58
否则,首先,将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);
等等。等等。等等。
发布于 2015-10-05 04:38:25
因为你想把一个八位数分成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;
}
https://stackoverflow.com/questions/32937864
复制相似问题