简体   繁体   English

用数字6代替数字5

[英]replace the digit 5 with 6 in a number

i want to replace 5 with 6 and print the number 我想用5代替5并打印数字

i want to replace 5 with 6 and print the number but i cant understand whats wrong in my code. 我想用6代替5并打印数字,但是我不明白我的代码有什么问题。 for instance when i give 200 the output should be same ie 200 but it gives 199 and when i give 205 as input instead of giving 206 as output it gives 205 itself. 例如,当我给出200时,输出应该相同,即200,但给出199,而当我给出205作为输入而不是给出206作为输出时,它给出205本身。

#include<stdio.h>
#include<math.h>
int main()
{
    int n,i=0,r,sum=0;
    while(1){
        printf("\nenter no\n");
        scanf("%d",&n);
        while(n>0)
        {
            r=n%10;
            printf("r is= %d\n",r);
            if(r==5)
            {
                r=6;
            }
            sum=sum+(r*pow(10,i));
            n=n/10;
            i++;
        }
        printf("new no is:\t %d",sum);
        sum=0;i=0;
    }
    return 0;
}

Like others have noted, it's a floating-point arithmetic problem, the value pow outputs is little bit less than the desired value (ie. getting 199.999999 instead of 200, so it gets rounded to 199). 就像其他人指出的那样,这是一个浮点算术问题, pow输出的值略小于所需值(即,获取199.999999而不是200,因此将其舍入为199)。 There is a similar post about this behaviour. 关于此行为也有类似的帖子。

Anyway, if you just want it to work you could replace this line: 无论如何,如果您只希望它能正常工作,则可以替换此行:

sum=sum+(r*pow(10,i));

with: 与:

 sum=sum+(r*(int)(pow(10,i)+0.5));

and it will get rounded just right. 它将四舍五入到正确的位置。 Once again, this is just a fast solution that'll help you make the program work, as I assume you are a begginer in C. 再次,这只是一个快速的解决方案,可以帮助您使程序正常运行,因为我认为您是C语言的入门者。

But I STRONGLY advise you to read about the floating-point arithmetic behaviour in programming languages, and why using pow on integers is a bad practice in C/C++. 但是我强烈建议您阅读编程语言中的浮点算术行为,以及为什么在C / C ++中对整数使用pow是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM