点击蓝字
关注我们
1
示例程序
#includeint main(void){
float weight; float value; printf("Are you worth your weight in rhodium?\n"); printf("Let's check it out.\n"); printf("Please enter your weight in pounds: "); /* 从用户处获取输入 */ scanf_s("%f", &weight); /* 衡量转换 */ value = float(770 * weight * 14.5833); printf("Your weight in rhodium is worth $%.2f.\n", value); printf("You are easily worth that! If rhodium price drop,\n"); printf("eat more to maintain your value.\n"); return 0;}
注意
①warning:从“double”转换到“float”,可能丢失数据
value = 770 * weight * 14.5833→value = float(770 * weight * 14.5833)使用强制类型转换
②scanf和scanf_s区别
scanf()不会检查输入边界,可能造成数据溢出。scanf_s()会进行边界检查。_s后缀的函数是为了让原版函数更安全,传入一个和参数有关的大小值,避免引用到不存在的元素,防止hacker利用原版的不安全性(漏洞)黑掉系统。
代码解释
①变量声明:整形变量int型;浮点型变量float型可以处理带有小数点的数字;
②打印float型变量时使用%f说明符来处理浮点值,使用%.2f中的.2修饰可精确控制输出格式,使得浮点数显示小数点后两位;
③使用scanf_s函数为程序提供键盘输入,%f表明函数从键盘中读取一个浮点数,&weight表明输入值将赋值存储于weight的变量中,使用&符号指示weight变量的位置
2
变量和变量数据
在程序使用之前预先设定并在整个运行过程中没有变化的数据叫做常量;
在程序运行过程中可能变化的数据叫做变量;
数据类型关键字
数据类型关键字 | 表示含义 |
---|---|
int | 整数类型 |
char | 字符类型,可表示字母及其他字符,或小的整数 |
float | 浮点型,表示带小数点的数 |
double | 浮点型,表示带小数点的数 |
组合long double | 浮点型,表示带小数点的数 |
_Bool | 布尔类型,表示布尔值[true和false] |
_Complex | 复数类型 |
_Imaginary | 虚数类型 |