“21好习惯”第一期-15

12 篇文章 0 订阅

C++心得笔记


今天做了几道例题,用来巩固和实践这几天学习的第三章处理数据的知识。


 习题一:计算BMI

        这道题的难度没有多大,只要按照要求用const符号常量表示各种转换因子就行。然后注意体重以磅为单位时要除以转换因子才能得到以千克为单位的体重,然后注意下是结果除以身高的平方就行。

#include<iostream>
int main()
{
    using namespace std;
    const int incun_per_inchi = 12;
    const float mi_per_incun = 0.0254;
    const float bang_per_kg = 2.2;

    float incun,inchi;
    float bang;
    cout << "Please enter your long:inchi and incun\n ";
    cin >> inchi >> incun;
    cout << "Please enter your weight : how bang\n";
    cin >> bang;
    cout << "Then I will tell your BMI= ";
    incun = incun + inchi * incun_per_inchi;
    double meter;
    meter = incun * mi_per_incun;
    double weight;
    weight = bang / bang_per_kg;
    double BMI;
    BMI = (weight / (meter * meter));
    cout << BMI <<endl;
    
    return 0;
}

输出如下:

   

 习题二: 将以度分秒表示的精度值用度来表示

 

        这道题比上一题更简单,用分,秒分别除以转换因子就行。注意结果的类型要变成高精度类型double!

#include<iostream>
using namespace std;
const int minutes_per_degree = 60;
const int seconds_per_minute = 60;
int main()
{
    int degree, minute, second;
    cout << "Enter a latitude in degrees, minutes, and seconds:\n";
    cout << "First,enter the degree:";
    cin >> degree;
    cout << "Next,enter the minutes of arc:";
    cin >> minute;
    cout << "Finally,enter the seconds of arc:";
    cin >> second;
    cout << "1degrees,2minutes,3seconds=";
    double latitude;
    latitude =(double) degree + (double)minute / minutes_per_degree + (double)second / seconds_per_minute / minutes_per_degree;
    cout << latitude <<"degrees" << endl;
    return 0;
}

输出如下:

  

讲解:强制类型转换的优先级为 2,大于乘除运算的优先级(3 级)。

因此在上面语句中,最先执行的是把 degree,minute 转换为 double 类型。

习题三: 将秒转化为天时分秒

 

        这道题思路是先由总的秒数用除法计算成分钟,然后求余得到剩余的秒数,接着类似,求出小时,得到剩余的分钟,最后求出天数,计算得到剩余的小时。

#include<iostream>
using namespace std;
const int hours_per_day = 24; 
const int minutes_per_hour = 60;
const int seconds_per_minute = 60;
int main()
{
    long seconds;
    cout << "Enter the number of seconds:";
    cin >> seconds;
    cout << seconds << " seconds = ";
    int minutes, hours, days;
    minutes = seconds / seconds_per_minute;
    seconds = seconds % seconds_per_minute;
    hours = minutes / minutes_per_hour;
    minutes = minutes % minutes_per_hour;
    days = hours / hours_per_day;
    hours = hours % hours_per_day; 
    cout << days << " days," << hours << " hours," << minutes << " minutes, " << seconds << " seconds" <<endl;
    return 0;
}

 输出如下:

讲解:本题提示了要将秒设置成Long或long long类型,为何?

           因为将second设置成short int . 会数据溢出,31600000已经超过了short int 类型能表示的最大数据。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值