[英]I'm trying to make a function that converts integer to string which is not returning the string. How can I solve this?
[英]How can I store a digit of an Integer I'm trying to separating?
我遇到的问题是,我想取一个整数并将其分开。 例如:用户输入:23432。控制台应该打印“2 3 4 3 2。我遇到的问题是存储这些数字。例如,
User Input : 2020
assign input to num.
digit = 2020 % 10 = 0 <--- 1st Digit
num = num / 10 = 202
digit2 = num % 10 = 2 <--- 2nd Digit
num = num / 100 = 20.2
temp = round(num) = 20
digit3 = num % 10 = 0 <--- 3rd Digit
digit4 = num / 10 = 2 <---- 4th Digit
这种方法的问题在于它依赖于用户输入,我使用的范围是 1-32767,所以我不知道要创建多少个数字变量。 使用我创建的结构,有人可以帮助它以某种方式运行,无论数字是什么,数字都以我描述的方式保存和打印吗?
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
int rem = num % 10;
return rem;
}
int Div(int num){
int div = num / 10;
return div;
}
这种方法的问题在于它依赖于用户输入,我使用的范围是 1-32767,所以我不知道要创建多少个数字变量。
所以计算一下。 您可以通过每次将变量增加 10 倍,直到再增加一次使其大于输入数字来做到这一点:
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
int div = 1;
while(div * 10 <= num)
div *= 10;
然后你可以重复将你的数字除以这个除数来得到每个数字,每次将除数除以 10 一次移动一个位置:
printf("The digits in the number are: ");
while(div > 0)
{
printf("%d ", (num / div) % 10);
div /= 10;
}
这是一个非常复杂的方法。 为什么不读取字符串,并像这样解析字符串:
int main(void) {
char buf[256]; // should be big enough, right? 10^256-1
memset(buf, 0, 256];
puts("enter something : ");
if( NULL == fgets(STDIN, 255, buf)) {
perror("Egad! Something went wrong!");
exit(1);
}
// at this point, you already have all the input in the buf variable
for(int i=0; buf[i]; i++) {
putchar( buf[i] ); // put out the number
putchar( ' ' ); // put out a space
}
putchar( '\n' ); // make a nice newline
}
如上所述,它允许任何字符,而不仅仅是数字。 如果您想限制为数字,您可以过滤输入,或在 for 循环中进行检查……这取决于您要完成的任务。
C 允许您非常优雅地处理问题的一种方法是通过递归。
考虑一个例程,它只知道如何打印数字的最后一位,如果需要,前面有一个空格。
void printWithSpaces(int neblod)
{
// Take everything except the last digit.
int mene = neblod / 10;
// Now extract the last digit
int fhtagn = neblod % 10;
// Check if there are leading digits
if (mene != 0)
{
// There are, so do some magic to deal with the leading digits
// And print the intervening space.
putchar(' ');
}
putchar(fhtagn + '0');
}
好的。 所以这很好,除了我们可以用什么来“做一些魔术来处理前导数字”?
难道我们不想将它们打印为数字序列,并带有合适的中间空格吗?
这不正是void printWithSpaces(int neblod)
所做的吗?
所以我们做一个改变:
void printWithSpaces(int neblod)
{
// Take everything except the last digit.
int mene = neblod / 10;
// Now extract the last digit
int fhtagn = neblod % 10;
// Check if there are leading digits
if (mene != 0)
{
// There are, so print them out
printWithSpaces(mene);
// And print the intervening space.
putchar(' ');
}
putchar(fhtagn + '0');
}
你已经完成了。
对于好奇的人,以下关于 C 递归的文章可能会提供一个有趣的阅读,以及对我稍微不寻常的变量名称选择的一些见解。 ;) http://www.bobhobbs.com/files/kr_lovecraft.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.