初始化数组的几种方式、格式化输出浮点数、round函数、ceil函数、floor函数

初始化数组的几种方式

  • memset,在<cstring>头文件中。memset按照字节来赋值。只能使用memset初始化为0,-1,或者一个特别大的数;

    • int a[100];
      memset(a, 0, sizeof(int) * 100);
      memset(a, -1, sizeof(int) * 100);
      
  • 使用fill()函数和fill_n()函数,这俩函数都在algorithm头文件中。

    • int a[100];
      fill(a, a + 100, 2);
      vector<int> nums(100);
      fill(nums.begin(), nums.end(), 2);
      
      fill_n(a, 5, -3);	//第一个参数是地址,第二个参数是个数,第三个参数是填充值
      

格式化输出

使用printf()函数格式化输出浮点数

double d = 1563.1415926;
printf("%f\n", d);		//1563.141593
printf("%8.3f\n", d);	//1563.142
//使用上面的方法小数点会有四舍五入的问题
//避免四舍五入的方法是使用floor函数
double a = floor(d * 1000.0) / 1000.0;

round函数、ceil函数、floor函数

这三个函数都在math.h头文件中;

  • floor函数:把一个浮点数向下取整,函数原型为double floor(double x)floor函数把转换后的结构强转为int类型。

    • int main()
      {
          double i = floor(2.2);
          double j = floor(-2.2);
          printf("The floor of 2.2 is %f\n", i);	//2
          printf("The floor of 2.2 is %f\n", j);	//-3
          system("pause");
          return 0;
      } 
      
  • ceil函数:把一个浮点数向上取整,函数原型为double ceil(double x);返回一个double类型的数,默认有6位小数;

    • int main()
      {
          double i = ceil(2.2);
          double j = ceil(-2.2);
          printf("The ceil of 2.2 is %f\n", i);
          printf("The ceil of 2.2 is %f\n", j);
          system("pause");
      	return 0;
      }
      //输出
      //The ceil of 2.2 is 3.000000
      //The ceil of 2.2 is -2.000000
      
  • round函数:把一个浮点数四舍五入,

    • int main()
      {
          double i = round(2.215);
          double x = round(2.7);
          double j = round(-2.2);
          double y = round(-2.7);
          printf("The round of 2.2 is %f\n", i);
          printf("The round of 2.7 is %f\n", x);
          printf("The round of -2.2 is %f\n", j);
          printf("The round of -2.7 is %f\n", y);
          system("pause");
          return 0;
      }
      
      /*
      The round of 2.2 is 2.000000
      The round of 2.7 is 3.000000
      The round of -2.2 is -2.000000
      The round of -2.7 is -3.000000
      */
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值