• C Primer Plus(6) 中文版 第3章 数据和C 3.1 示例程序


    程序离不开数据。
    C语言的两大数据类型:整数类型和浮点数类型。
    3.1 示例程序
    /* platinum.c  -- your weight in platinum */
    #include
    int main(void)
    {
        float weight;    /* user weight             */
        float value;     /* platinum equivalent     */
        
        printf("Are you worth your weight in platinum?\n");
        printf("Let's check it out.\n");
        printf("Please enter your weight in pounds: ");
        
        /* get input from the user                     */
        scanf("%f", &weight);
        /* assume platinum is $1700 per ounce          */
        /* 14.5833 converts pounds avd. to ounces troy */
        value = 1700.0 * weight * 14.5833;
        printf("Your weight in platinum is worth $%.2f.\n", value);
        printf("You are easily worth that! If platinum prices drop,\n");
        printf("eat more to maintain your value.\n");
        
        return 0;

    /* 输出:

    */

    提示 错误与警告
    即使输入正确无误,编译器可能给出一些警告。例如:
    “从double类型转换为float类型可能会丢失数据”错误信息表明程序中有错,不能进行编译。警告则表明,尽管编写的代码有效,但可能不是程序员想要的。警告并不终止编译。
    scanf( "%f", &weight );如果输入的不是数字,会导致程序出问题。
    程序调整
    需要调用两次getchar()函数的情况:
    第1次调用getchar()是为了读取输入的换行符;
    第2次调用getchar()是为了让程序暂停,等待输入。
    3.1.1 程序中的新元素
    float表示浮点数类型,可以处理更大范围的数据。
    printf()中使用%f来处理浮点值。%.2f中的.2用于精度控制输出,指定输出的浮点数只显示小数点后面两位。
    scanf()函数用于读取键盘的输入。%f说明scanf()要读取用户从键盘输入的浮点数,&weight告诉scanf()把输入的值赋值给weight的变量。scanf()函数使用&符号表明找到weight变量的地点。
    交互式程序使用起来更有趣,也更加灵活。
    printf()和scanf()两个函数结合起来,就可以建立人机双向通信。 

  • 相关阅读:
    uni-app使用支付宝小程序开发者工具开发钉钉小程序
    c++ SFML ftp切换工作目录并且重命名目录
    【无标题】乐观与悲观
    电脑如何查看代理服务器IP?
    基于YOLOv5的钢材表面缺陷检测
    【2024.6.23】今日科技时事:科技前沿大事件
    【sleuth + zipkin 服务链路追踪】
    旧系统改造
    GEO生信数据挖掘(九)WGCNA分析
    Qt5开发从入门到精通——第七篇三节( 图形视图—— 图元创建 GraphicsItem V1.0)
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126135613