Menu
CoddyTech

浮点数与双精度数

本课属于 Coddy C 学习旅程的“基础知识”单元。第 7 课,共 63 课。

float 和 double 是在 C 中用于存储小数的数据类型。

声明一个浮点型变量:

float price = 19.99f;

注意后缀 'f',它告诉 C 这是一个浮点值。

声明一个 double 变量:

double pi = 3.14159265359;

float 和 double 的主要区别:

  1. 精度:double 的精度高于 float
    • float:约 7 位十进制数字
    • double:约 15 位十进制数字
  1. 大小:
    • Float:4 字节
    • Double:8 字节
  1. 范围:
    • Float:1.2E-38 到 3.4E+38
    • Double:2.3E-308 到 1.7E+308

打印一个浮点数值:

float temperature = 98.6f;
printf("Temperature is %f degrees\n", temperature);

按指定的小数位数打印:

printf("Temperature is %.1f degrees\n", temperature);

这会显示:“Temperature is 98.6 degrees”

challenge icon

挑战

简单

编写一个程序,完成以下操作:

  1. 声明一个名为 celsius 的 float 变量
  2. 声明一个名为 fahrenheit 的 double 变量
  3. 将值 25.0 赋给 celsius
  4. 使用以下公式将 celsius 转换为 fahrenheit:fahrenheit = (celsius * 9.0/5.0) + 32.0
  5. 打印结果,格式如下:
    25.0 degrees Celsius is equal to 77.0 degrees Fahrenheit

确保输出恰好显示一位小数。Celsius 和 Fahrenheit 的拼写必须完全一致。

要在一个 printf 中打印两个变量,请为每个数字使用 %.1f 作为占位符。将 celsius 和 fahrenheit 替换为你实际使用的变量名:

printf("%.1f degrees Celsius is equal to %.1f degrees Fahrenheit\n", celsius, fahrenheit);

这里,第一个 %.1f 会替换为 celsius 的值,第二个 %.1f 会替换为 fahrenheit 的值。末尾的 \n 会将光标移到新的一行。

亲手试试

#include <stdio.h>

int main() {
    // 在这里编写你的代码
    
    
    printf("%.1f degrees Celsius is equal to %.1f degrees Fahrenheit\n", celsius, fahrenheit);
    return 0;
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: C 在线编译器