#include<stdio.h>
#include<math.h>
void main()
{
int num, rem, no = 0, i = 0;
printf("Enter a number: ");
scanf("%d", &num);
do
{
rem = num % 10;
if(rem == 9)
{
rem = 0;
} else {
rem = rem + 1;
}
no = no + (rem * pow(10,i++));
num = num / 10;
} while(num != 0);
printf("new no: %d\n", no);
}
此代码是为用户输入的数字的每个数字加1,并且2位数字正常工作但是当我输入3位数字时,例如:123,输出是233而不是234
答案 0 :(得分:2)
你的代码运行正常,但它可能是其他人建议的浮点舍入的结果。而不是使用pow
函数,在单独的变量中跟踪10的当前功率,并在每次迭代时乘以10。
#include<stdio.h>
int main() // main should always return int, not void
{
int num, rem, no=0,i=0,p=1; // p is the current power of 10
printf("Enter a number: ");
scanf("%d", &num);
do{
rem=num%10;
if(rem==9)
{
rem=0;
}else{
rem=rem+1;
}
no+=rem*p; // multiply by the current power of 10
p*=10; // increase the power of 10
num=num/10;
}while(num!=0);
printf("new no: %d\n", no);
return 0;
}