初始化数组的几种方式
-
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 */
-