C Primer Plus (第6版)第三章编程练习

第三章 数据和C

2. 编写一个程序,要求提示输入一个ASCII码值(如66),然后打印输入的字符。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ascii;
    printf("Enter an ASCII code: ");
    scanf("%d", &ascii);
    printf("%d is the ASCII code for %c!", ascii, ascii);
    return 0;
}

4. 编写一个程序,读取一个浮点数,先打印成小数点形式,再打印成指数形式。然后,如果系统支持,再打印成p记数法(即十六进制记数法)。按以下格式输出(实际显示的指数位数因系统而异):

Enter a floating-point value: 64.25

fixed-point notation: 64.250000

exponential notation: 6.425000e+01

p notation: 0x1.01p+6

#include <stdio.h>
#include <stdlib.h>
int main()
{
    float num;

    printf("Enter a floating-point value: ");
    scanf("%f", &num);
    printf("fixed-point notation:%f\n", num);
    printf("exponential notation:%e\n", num);
    printf("p notation:%a\n", num);
    return 0;
}

5. 一年大约有3.156E7秒。编写一个程序,提示用户输入年龄,然后显示该年龄对应的秒数。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    long year_second = 3.156e7;
    int age;
    long seconds;
    printf("Enter your age: ");
    scanf("%d", &age);
    seconds = age * year_second;
    printf("The numberof seconds to age %d is %ld!\n", age, seconds);
    return 0;
}

6. 1个水分子的质量约为3.0E-23克。1夸脱水大约是950克。编写一个程序,提示用户输入水的夸脱数,并显示水分子的数量。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    float mass_mol = 3.0e-23;
    float mass_qt = 950;
    float quarts;
    float molecules;
    printf("Enter the number of quarts of water: ");
    scanf("%f", &quarts);
    molecules = quarts * mass_qt / mass_mol;
    printf("%f quarts of water contain %e molecules.\n", quarts, molecules);
    return 0;
}

8. 在美国的体积测量系统中,1品脱等于2杯,1杯等于8盎司,1盎司等于2大汤勺,1大汤勺等于3茶勺。编写一个程序,提示用户输入杯数,并以品脱、盎司、汤勺、茶勺为单位显示等价容量。思考对于该程序,为何使用浮点类型比整数类型更合适。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    float cups;
    float pints;
    float ounces;
    float bigspoons;
    float teaspoons;
    printf("Enter the number of cups: ");
    scanf("%f", &cups);
    pints = cups / 2;
    printf("%.2f cups is %.2f pints.\n", cups, pints);
    ounces = cups * 8;
    printf("%.2f cups is %.2f ounces.\n", cups, ounces);
    bigspoons = ounces * 2;
    printf("%.2f cups is %.2f bigspoons.\n", cups, bigspoons);
    teaspoons = bigspoons * 3;
    printf("%.2f cups is %.2f teaspoons.\n", cups, teaspoons);
    return 0;
}

假如pints用整数类型的话,如果杯数是5.5杯,那么pints就会舍去小数位的数字,从而不会那么精确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值