void main()
{
int i, j = 0, p, q, N; // N is the integer and p is the position needed
printf("Enter two positive integers: ");
scanf("%d%d", &N, &p); // Taking the values of N and p
for(i = 1; i <= p; i++) {
j = N / 10;
q = j % 10;
i++;
j = q;
}
printf("The digit of %d in the position %d is %d", N, p, j);
}
示例输入:
输入两个正整数:
123456789个
3
输出:
The digit of 123456789 in the position 3 is 8
上面的代码行实际上有2个问题:
j
的新值在第二次运行时工作答案 0 :(得分:0)
#include <stdio.h>
int main()
{
int i=0;
int j=0;
int p=5;
int n = 123456;
int digits[12]={};
j=n;
while(j)
{
digits[i]=j%10;
j = j/10;
i++;
}
printf("The digit of %d in the position %d is %d",n,p,digits[i-p]);
return 0;
}
我设计的最简单方法是将整数转换为数字并查找。
为什么这样:
要避免pow
,log10
,因为它们需要浮点支持才能运行,而硬件浮点运行速度很快。
避免两个循环,因为这两个循环会进行大量的重复计算。
答案 1 :(得分:0)
首先计算整数中的位数,比如n
。然后你可以通过将数字除以 10 n-1 来获得第一个数字强>。然后把它放在循环中并通过 1 &amp;降低 n 。数字 N by
N%= 10 n-1
int main()
{
int i,j=0,p,N;
printf("Enter two positive integers: ");
scanf("%d%d",&N,&p);
int pow=1,tmp=N;
//counting power of 10 to divide
while(tmp>10)
{
pow*=10;
tmp/=10;
}
tmp=N;
for(i=1; i<=p;i++){
j = tmp/pow;
tmp%=pow;
pow/=10;
}
printf("The digit of %d in the position %d is %d\n",N,p,j);
}
答案 2 :(得分:0)
有几种方法可以做到这一点。正如一些评论所暗示的那样,您可以执行以下任一操作:
方法1:
将数字转换为字符串数组,可以通过sprintf
完成。
char str[256];
int len = sprintf(str,"%d",N);
//traverse str using len
方法2:
由于基数b中有n个数字的数字N,您可以表达任何数字,最多pow(b,n)-1
。要获得数字,您可以使用pow
的反函数,即base-b对数。您可能无法获得整数值,因此您可以使用floor
并将结果转换为int。完整的程序如下所示:
#include <stdio.h>
#include <math.h>
int getDigit(int num, int p)
{
return (num / (int)pow(10, floor(log10(num)) - p)) % 10;
}
int main()
{
int i,j=0,p,q,N;// N is the integer and p is the position needed
printf("Enter two positive integers: ");
scanf("%d%d",&N,&p);// Taking the values of N and p
j = getDigit(N,p);
//The result is j if you count from 0, j+1 if you count from 1
printf("The digit of %d in the position %d is %d\n",N,p,j+1);
return 0;
}
答案 3 :(得分:0)
不使用2个循环:
int main()
{
int i,ans,p,N,no_of_digits=0,temp;
printf("Enter two positive integers: ");
scanf("%d%d",&N,&p);
temp=N;
no_of_digits=(int)log10(N) + 1;
while(i<=(no_of_digits-p))
{
ans=N%10;
N=N/10;
i++;
}
printf("The digit of %d in the position %d is %d\n",temp,p,ans);
}
答案 4 :(得分:0)
#include <stdio.h>
int getDgtLen (int n);
int main(void)
{
// n is the integer and p is the position needed
int i, q, n, p;
// Prompt for taking the values of n and p
do
{
printf("Enter two positive integers for number, position: ");
scanf("%d%d", &n, &p);
}
while (n < 0 || p <= 0);
int nOrigin = n;
int len = getDgtLen(n);
if (p <= len)
{
for (i = 0; i < p; i++)
{
q = n % 10;
n /= 10;
}
printf("The digit of %d in the position %d is %d\n", nOrigin, p, len - q + 1);
}
else
{
printf("position not found!\n");
}
}
int getDgtLen (int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}