c++中的Double函数

Double Function in C++

本文关键字:函数 Double 中的 c++      更新时间:2023-10-16

我被第3.3章c++的原理和实践卡住了:

他提到:-让"姓名和年龄"示例运行。然后,将其修改为以月为单位写出年龄:以年为单位读取输入,然后(使用*运算符)乘以12。把年龄读成a两倍是为了让孩子们为自己五岁半感到骄傲而不是只有五个。

下面是我运行的没有问题的姓名和年龄示例:

    #include "std_lib_facilities.h"
    int main()
    {
    cout << "Please enter your name and age.n";
    string name;            //string variable
    int age;                //integer variable
    cin >> name >> age;     //reads string and integer
    cout << "Hello, " << name << " (Age: " << age << ")n";
    }

之后,我尝试将年龄改为月,我可以通过使用以下命令来实现:

    #include "std_lib_facilities.h"
    int main()
    {
    cout << "Please enter your name and agen";
    string name;
    int age;
    cin >> name >> age;
    cout << "Hello, " << name << " (Age: " << age * 12 << " Months Old)n";
    }

所以问题仍然是,我如何"将年龄读入双精度体"?尽管我设法让我的输出以月为单位显示年龄,但我认为我还没有清楚地理解处理这个问题的方法。

仅使用double作为读取数据的变量类型。

// What is this?    
//#include "std_lib_facilities.h"
#include <iostream>
#include <string>
using std::cout;
using std::string;
using std::cin;
int main()
{
    cout << "Please enter your name and agen";
    string name;
    double age;
    cin >> name >> age;
    cout << "Hello, " << name << " (Age: " << age * 12 << " Months Old)n";
    return 0;
}

直接声明age为double。你的问题应该得到解决。

样例代码

#include "std_lib_facilities.h"
int main()
{
cout << "Please enter your name and agen";
string name;
double age;
cin >> name >> age;
cout << "Hello, " << name << " (Age: " << age * 12 << " Months Old)n";
}

现在程序应该可以正常运行了

相关文章: