2

这不是作业问题,我只是好奇。如果我有一个计算 3 位数字的程序,比如 123,我怎么才能得到“1”?我试图在最后打印一条消息,上面写着“(第一个数字)告诉你......并且(最后两个数字)告诉你......”但我不确定如何保存或获取该单曲数字。有任何想法吗?除了使用数组之外,还有更简单的方法吗?谢谢。

4

3 回答 3

6

您可以使用整数除法100

#include <stdio.h>

int main()
{
  printf( "%d\n", 123/100 ) ;

  return 0 ;
}

更通用的方法是使用后续轮次的模数10和整数除法10来删除最后一个数字,直到数字小于10

int num = 123 ;
while( num >= 10 )
{
    printf( "%d\n", num % 10 ) ;
    num = num / 10 ;
}
printf( "%d\n", num  ) ;

如果您可以从最后一个到第一个以相反的顺序显示您的数字,则此方法不需要任何额外的存储空间,否则您可以将结果存储在一个数组中。

于 2013-07-17T03:04:14.817 回答
1
  • 获取数字的长度。
  • 迭代并获取每个数字。

这是一个示例:

#include <stdio.h>
#include <math.h>

int main ()
{
  int n = 123, i; char buffer [33];

  int len = n==0 ? 1 : floor(log10l(abs(n)))+1;

  for(i=n;len--; i=(int)(i/10)) buffer[len] = (i%10);

  printf("%d", buffer[0]);   // First Digit
  printf("%d", buffer[1]);   // Second Digit
  printf("%d", buffer[2]);   // Third Digit... so on

  return 0;
}
于 2013-07-17T03:32:32.593 回答
0

如果您想以简单的方式进行操作,我的意思是,如果您想让它仅针对一个数字(例如 123)进行编程,那么 Shafik 的第一个示例就足够了。

如果您想从末尾取出数字,那么 Shafik 的第二个示例就足够了。

欢迎提出建议,如果有人看到改进,谢谢:)

从头开始取出数字怎么样,这是我对您问题的不同看法,我从头开始取出数字是这样的:

#include<stdio.h>
int main()
{
  int di , i , num , pow = 1;
  setbuf ( stdout , NULL);
  printf ("enter the number of digits of the number\n");// specify at run time what will be the number of digits of the array.
  scanf ( "%d" , &di);
  int a[di];

  printf ("enter the %d digit number:\n",di);// 
  scanf ( "%d" , &num);//One thing is to be noted here that user can enter more digits than specified above , It is up to user to enter the specified digits , you can improve this program by making a check whether user enters the specified digits or not , better do it as exercise.
  while( di > 1 )
    {
    pow = pow * 10;
    di--;
    }

  i = 0;
  while ( num > 0)
    {
      a[i]=num/pow;
      num=num%pow;
      pow=pow/10;
      i++;
    }
  printf("the digits from the beginning are :\n"); 
  for(int j = 0 ; j < i ; j++)
    printf("%d\n",a[j]);
  return 0;
}

重要——当使用数组存储数字时,如果用户输入的数字多于指定的数字,那么多余的数字将作为数组的第一个元素打印,正如我所说,如果你愿意,你可以进一步改进这个程序并对用户进行检查输入位数,祝你好运:)

注意——这只是看待问题的不同方式,两种解决方案最终都会产生相同的结果。我只是想这样说。

于 2013-07-17T04:08:52.637 回答