将int重新设置为从厘米到米的双倍到州高度c ++

时间:2018-02-25 11:18:08

标签: c++

#include <iostream> // try to convert height in centimeters to meters

using namespace std;

int main()
    {
        int height_cm ; // declaring first int in centimeters
        cout << " State your height in centimeters: " << endl ; // stating
        cin >> height_cm ; /* I was thinking also of storing this value for later reusage in retyping but I don´t know how to do it */
        double (height_cm) ; /* here is the problem,debugger says that I can not declare height_cm again because I had declared it as int before , but I´m actually trying to retype it */
        height_cm /= 100 ; /* I´m also not sure about this , I think this assignment should be possible to get number in meters */
        cout << " Your height in meters is: " << height_cm << endl ; /* this should give me height in meters */
        return 0 ;
    }

1 个答案:

答案 0 :(得分:0)

问题在于,正如您的编译器所说的那样,您试图为另一个变量使用相同的名称(height_cm)。尝试做:

...
double height_m = height_cm/100.0;
cout << " Your height in meters is: " << height_m<< endl ;
...

这样,meter变量将有一个新名称,编译器将编译。此外,请注意我将height_cm除以100.0而不是100。这是因为100int100.0floatdouble。如果您使用int,则会有int division意味着您将丢失小数部分。

其中的一部分:

  • 我还考虑存储此值以供以后在重新输入中使用但我不知道如何操作cin>>height_cm;代码接受用户键入的任何内容,将其转换为到int并将其存储在名为height_cm的变量中,您可以在当前函数中随时使用该变量(在本例中为main())。
  • 我也不确定这一点,我认为这个分配应该可以获得以米为单位的数字:该代码可以编译没有问题。但是,最终会得到一个int divison。如果你想要你能做到:

代码:

...
double height_m(height_cm);// this converts the int to double and stores it in the new variable height_m
height_m /= 100;// Divide the double variable height_m by 100 and store it again in height_m
...

请注意,在这种情况下,虽然您使用的100代替100.0而不是int分区,因为height_mdouble。< / p>