#include
#include
unsigned fun(int w)
{
int a;
int i;
i=1;
a=w;
while(a==0)
{
a=a/10;
i++;
}
w=w%pow(10,i);
return w;
}
unsigned main()
{
int w;
printf("please enter a number:\n");
scanf("%d",&w);
printf("the result is:%u\n",fun(w));
return 0;
}
若w是n (n≥2)位的整数,函数求出w的后n-1位的数作为函数值返回。
自己写的算法,所以特别想实现,看过网上的答案,没太明白......
求详细解释
int fun(int n){
int nn = n;
int r = 1;
while( nn >= 10 ){
r = r * 10;
nn /= 10;
}
return n % r;
}
while(a==0)
{
a=a/10;
i++;
}
这是求出有几位数,然后
w=w%pow(10,i);
这个算出10的N-1次方
然后通过整除这个数字得到尾数,比如1234
得到4位数
第二步得到1000
最后让1234 % 1000,得到234
希望采纳我的回答哦。我是最先回答的请看清。最近抄袭回答比较猖獗。
i应该初始化为0。
不然后面位数计算不对。
fun函数有点问题,改改
unsigned fun(int w)
{
int a;
int i;
i=0;
a=w;
while(a>=10) //==0就进不来了,不能除到个位
{
a=a/10;
i++;
}
w=w%int(pow(float(10),float(i)));
return w;
}
你的代码太繁琐,用log10就可以
我写了一个,通过在线编译:
http://codepad.org/39Uw5z4F
输出234
#include<stdio.h>
#include<math.h>
int foo(int n)
{
int r = 1, i = 1;
for (i = 1; i <= (int)log10(n); i++)
r *= 10;
return n % r;
}
int main()
{
int x = 1234;
printf("%d", foo(x));
}
顺便请你复习下初中数学
y=log10(x)就是求
10的y次方=x。对y取整就是这个数字是几位数
先要转换成浮点数
pow()的返回值类型是double,%运算双方不能是实数类型。