反转用户输入的号码 [英] reversing numbers input by user
问题描述
我试图反转用户输入的数字(即只要用户输入正数,用户输入的数字就会存储在数组中)。
但是,当我输入
123 4569 752 896 -1
时,输出是
321 9653 257 698
正如你所看到的第二个数字不是9654。无法修复它。
#include< stdio.h>
#include< math.h>
//找到位数
int bsm(int a){
int i = 0;
while(a!= 0){
i ++;
a = a / 10;
}
返回i;
//倒数
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;
}
归还金额;
int main()
{
int i = 0,k,a [10],p,r;
scanf(%d,& a [i]);
while(a [i]> 0){
i ++;
scanf(%d,& a [i]); (k = 0; k p = bsm(a [k])的
}
;
r = rev(p,a [k]);
printf(\\\
%d,r);
}
返回0;
我将限制我的答案为两个提示。
-
当您使用
pow()
,它返回一个浮点数,并且浮点数是不精确的。使用 only 整数数学或字符串重写您的程序。 考虑如何处理以零为结尾的数字;例如,2000年应该是什么情况?
I'm trying to reverse the numbers input by user (i.e. 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.
#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. 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?
这篇关于反转用户输入的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!