+ 2
kaleidoscope problem my program is rounding the second decimal place one less than what its supposed to be
Can anyone tell me what I wrote wrong #include <stdio.h> int main() { float price,n; scanf("%f",&n); if(n==1) { price=5; } else if(n>1) { price=(5*n)-((5*n)*0.1); } price+=price*0.07; printf("%.2f",price); return 0; }
14 odpowiedzi
+ 1
+ 4
well, first of all it's weird that you're making n a float instead of an int, and it's maybe possible there are some rounding consequences from that . . . but that aside if you think it's a rounding problem, you can:
a) switch to doubles
b) try to cut down on the number of separate operations (ie bake taxes into the n=1 case and combine *0.9 and *1.07 into a single operation, instead of doing the taxes separately)
There's another possibility though, which is that they secretly want you to always round up fractions of a cent (which would be pretty common in real-world business practice, but they still really should have stated it explicitly if so), in which case you'd probably just wanna include Math.h and use ceil(). I don't know if that's what they wanted here, but I would try this approach first anyway, since rounding errors are much messier to troubleshoot
+ 3
Hello!
Please, upload a private code with your snippet.
You should read this: https://code.sololearn.com/Wek0V1MyIR2r/?ref=app
+ 3
https://www.sololearn.com/Discuss/3085069/?ref=app
https://www.sololearn.com/Discuss/2486871/?ref=app
+ 2
You can try using ceil() (remember to #include <math.h>)
+ 2
That's not really a solution more like a way around the problem 🤔
+ 1
I first declared n as int itself but that still didn't solve it so I tried making n a float to see if itll fix anything but it didn't
+ 1
I tried it still isn't working 🥲giving thr same output
+ 1
But when I add 0.001 to the price it passes all the test cases
so it's definitely a small round up error
+ 1
And what if you try adding 0.001 to the result?
+ 1
0.01 doesn't work but 0.001 works
+ 1
So it is solved no?
+ 1
Well if ceil didn't fix it, then try using doubles, and if that's not enough somehow, replace
price = 5 with price = 5*1.07 (or just 5.35), and
price = (5*n)...etc with price = n*5*0.9*1.07 (or just n*4.815), and delete price += price*0.07
If you still have issues after that, it's probably not a rounding error after all