1. Code
1#include <iostream>2#include <stdio.h>3#include <cmath>4 using namespacestd;5 //leave a floating-point number to be rounded with n decimal places6 voidMain ()7 { 8 floatA=55.3252, b=55.3248;//internal a=55.32199,9 intbit,mtp;Tenprintf"Please enter the number of decimal digits you want to keep: \ n"); Onescanf"%d",&bit); AMtp=pow ((float)Ten,(float) bit);//pay attention to the POW function overloading problem, need type match, convert to float or double - floatA1= (a*mtp+0.5)/(float) MTP; - floatA2= (int) (a*mtp+0.5)/(float) MTP;//dividend converted to int type, divisor converted to float type the floatB1= (b*mtp+0.5)/(float) MTP; - floatB2= (int) (b*mtp+0.5)/(float) MTP; -printf"a1=%f a2=%f b1=%f b2=%f\n", A1,A2,B1,B2); - if(bit==2) +printf"a1=%.2f a2=%.2f b1=%.2f b2=%.2f\n", A1,A2,B1,B2); - Else if(bit==3) +printf"a1=%.3f a2=%.3f b1=%.3f b2=%.3f\n", A1,A2,B1,B2); ASystem"Pause"); at}
2. Running Results
Rounding a floating-point number