这不是家庭作业问题,我只是好奇。如果我有一个计算3位数的程序,比如说123,我怎么才能只得到"1“呢?我试图在末尾打印一条消息,上面写着“(第一个数字)告诉you...and (最后两个数字)告诉你...”但我不确定如何保存或获取那个个位数。有什么想法吗?有没有比使用数组更简单的方法?谢谢。
发布于 2013-07-17 11:04:15
您可以使用整数除以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-17 11:32:33
下面是一个示例:
#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-17 12:08:53
如果你想用简单的方法,我的意思是,如果你想让它只针对一个数字编程,例如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;
}重要提示--当使用数组存储数字时,如果用户输入的数字比指定的多,那么额外的数字将打印为数组的第一个元素,正如我所说的,如果您愿意,您可以进一步改进此程序,并检查用户输入的数字,祝您好运:)
注意到--这只是一种看待问题的不同方式,两种解决方案最终将产生相同的结果。我只是想这么说。
https://stackoverflow.com/questions/17690360
复制相似问题