printf("%.0f",x); an alternative for round() function in C++ ! Is my attempt correct?

I can use:

double x=13.6; printf("%d",(int)round(x)); 

Alternatively:

double x=13.6; printf("%.0f",x); 

Both are giving same output i.e. 14.

I don't know how this alternative method is rounding off to the nearest integer! Will this pass every test?

Can anyone help me understand the workflow of the alternative code?

1 Answer

I would not call this an alternative. The round function returns a numeric output depending on the input type that can be further processed (numerically). All you're doing is printing the number. If this is your only intended use, then you've got yourself an alternative, yay!

As for reliability, printf() will work in all cases. According to cplusplus.com,

A format specifier follows this prototype: [see compatibility note below] %[flags][width][.precision][length]specifier

Since you want a precision of 0 decimal places, you are requesting rounding to nearest integer.

I suggest looking up function definitions before posting next time.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like