“21好习惯”第一期-15

“21好习惯”第一期-15,第1张

“21好习惯”第一期-15 C++心得笔记
今天做了几道例题,用来巩固和实践这几天学习的第三章处理数据的知识。
 习题一:计算BMI

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

#include
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 incunn ";
    cin >> inchi >> incun;
    cout << "Please enter your weight : how bangn";
    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 < 
 

输出如下:

   

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

 

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

#include
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
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" < 
 

 输出如下:

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

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5115139.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存