c++ - Formatting numbers to n decimal places without rounding -


i want create c++ program calculate average of 3 positive numbers

where (x,y,z)>0 , (x,y,z)<=10

i have code:

#include <iostream> #include <cstdio> #include <math.h>  using namespace std;  int main() {     int x,y,z;     cin >> x >> y >> z;     double x1,y1,z1,ma;     x1 = x;     y1 = y;     z1 = z;      if(x>0 && x<=10 && y>0 && y<=10 && z>0 && z<=10)         ma = (x1+y1+z1)/3;     else         return 0;      printf("%.2f" , ma);      return 0; } 

for x=9, y=9 , z=5 average 23/3=7.666666666666667 , when format 2 decimal places, result 7.67, want appear 7.66 not 7.67.

please, can me?

thank you!

without using other functions, do:

double x = (double)((int)(23 * 100 / 3)) / 100.0; 

or bit simpler:

double x = (double)(int)(23 * 100 / 3) / 100.0; 

the int cast truncates remaining digits (so there no rounding).

in c++11 there trunc() function that.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -