zoukankan      html  css  js  c++  java
  • 将浮点数四舍五入

    1. 代码

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<cmath>
     4 using namespace std;
     5 //将一个浮点数保留n位小数进行四舍五入
     6 void main() 
     7 { 
     8     float a=55.3252,b=55.3248;//内部a=55.32199,
     9     int bit,mtp;
    10     printf("请输入你要保留的小数位数:
    ");
    11     scanf("%d",&bit);
    12     mtp=pow((float)10,(float)bit);//注意pow函数重载问题,需要类型匹配,转化为float或double
    13     float a1=(a*mtp+0.5)/(float)mtp;
    14     float a2=(int)(a*mtp+0.5)/(float)mtp;//被除数转化为int型,除数转化为float型
    15     float b1=(b*mtp+0.5)/(float)mtp;
    16     float b2=(int)(b*mtp+0.5)/(float)mtp;
    17     printf("a1=%f    a2=%f    b1=%f    b2=%f
    ",a1,a2,b1,b2);
    18     if(bit==2)
    19     printf("a1=%.2f    a2=%.2f    b1=%.2f    b2=%.2f
    ",a1,a2,b1,b2);
    20     else if(bit==3)
    21     printf("a1=%.3f    a2=%.3f    b1=%.3f    b2=%.3f
    ",a1,a2,b1,b2);
    22     system("pause");
    23 }    

    2. 运行结果

  • 相关阅读:
    c++ stl常用
    c++流操作
    操作符重载operator
    函数指针和指针函数
    指针c艹
    Oracle 账户锁定问题解决办法
    java回收算法
    JDK与JRE的区别
    关于getClass().getClassLoader()
    After reading a picture than out a picture
  • 原文地址:https://www.cnblogs.com/dongyanxia1000/p/4910501.html
Copyright © 2011-2022 走看看