[英]reversing numbers input by user
I'm trying to reverse the numbers input by user (ie numbers input by user are stored in an array as long as he inputs a positive number ). 我正在尝试反转用户输入的数字(即,只要用户输入正数,用户输入的数字就会存储在数组中)。 However, when I input 123 4569 752 896 -1 the output is 321 9653 257 698 As you can see the second number is not 9654. I couldn't fix it. 然而,当我输入123 4569 752 896 -1的输出是321 9653 257 698正如可以看到第二个数字是不9654.我不能修复它。
#include <stdio.h>
#include <math.h>
// finding the number of digits
int bsm(int a){
int i=0;
while(a!=0){
i++;
a=a/10;
}
return i;
}
// reversing the number
int rev(int m,int a){
int s=0,sum=0;
while(a!=0){
s=a%10;
sum+=s*pow(10,m)/10;
m--;
a=a/10;
}
return sum;
}
int main()
{
int i=0,k,a[10],p,r;
scanf("%d",&a[i]);
while(a[i]>0){
i++;
scanf("%d",&a[i]);
}
for(k=0;k<i;k++){
p=bsm(a[k]);
r=rev(p,a[k]);
printf("\n%d ",r);
}
return 0;
}
Since this looks like homework, I'll limit my answer to two hints. 由于这看起来像是作业,因此我将回答限于两个提示。
When you use pow()
, it returns a floating-point number, and floating-point numbers are inexact. 使用pow()
,它将返回浮点数,并且浮点数不精确。 Rewrite your program using only integer maths or strings. 仅使用整数数学或字符串重写程序。
Think about how you wish to handle numbers that end in zeroes; 考虑一下您希望如何处理以零结尾的数字。 for example, what should be the reverse of 2000? 例如,2000的倒数应该是多少?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.