I am trying to make a program that rounds a number to the nearest power of 10, for example if the input is 25378 the output should be 25000, or if the input is 438864 the output should be 438000. My code is working fine for the first case but not for the second, can anyone help me?
#include <stdio.h>
#include <math.h>
int b(int x)
{
int k;
int m;
//int resultado;
k = log10(x); //4 //5
m = pow(10, k-1); //1000
resultado = (x/m)*m;
return resultado;
}
int test_b()
{
int x;
while(scanf("%d", &x) !=EOF)
{
int z = b(x);
printf("%d\n", z);
}
return 0;
}
int main()
{
test_b();
return 0;
}
CodePudding user response:
You talked about powers, maybe you also wanted to round numbers like 24 or 105 for example to the nearest "power" (as you say), in this case I think it is noticeable by the code that you are not rounding to a power but "to the number"(I will say it like this to make it easier to understand) that is multiplying and dividing as it is in the code.
As someone already say it you can do like this but maybe you need something more:
int b(int x)
{
return (x/1000) * 1000;
}
I think you maybe want to round number like 24 or 106 too so i think this is the best solution (but im not sure :) )
int b(int x)
{
int num;
if(x<=100)
{
num = (x/10)*10;
}
else if(x>100 && x<1000)
{
num = (x/100)*100;
}
else if (x>=1000)
{
num = (x/1000)*1000;
}
return num;
}
I dont know if you need that but in the case you need its here :)
CodePudding user response:
You're not rounding to the nearest power of 10. You're always rounding down, not to nearest, and it's always a multiple of 1000 (so you don't need to use log10()
to get the number of digits).
Divide by 1000 then multiply by 1000. Integer division will simply discard the fraction.
int b(int x)
{
return (x/1000) * 1000;
}