C++ 转换不工作

标签 c++

#include <iostream>
using namespace std;
/*Use void functions, they perform some action but do not return a value*/

//Function Protoype, input,read in feet and inches:
void input (double&  feet, double& inches);
//Function Prototype, calculate, calculate with given formulae.
void calculate(double& feet, double& inches);
//Function Prototype, output, outputs calculations to screen.
void output (double meters, double centimeters);  

int main () 
{
    double feet;
    double inches;
    char repeat;

    do
    {
        //Call input:
        input(feet, inches);
        //Call calculate:
        calculate(feet, inches);
        //Call output:
        output (feet, inches);
        cout << "\n";
        cout << "Repeat? (Y/N): ";
        cin >> repeat;
        cout << "\n";
    }
    while (repeat == 'Y' || repeat == 'y');
}

//Input function definition:
void input (double&  feet, double& inches)
{
    cout << "Please enter the length in feet" << endl;
    cin >> feet;

    cout << "Please enter the length in inches" << endl;
    cin >> inches;
}

//Calculate function definition, insert formulae here:
void calculate (double& feet, double& inches)
{

    feet = (feet * 0.3048);
     inches = (inches * 2.54);
}

//Output function definition:
void output (double meters, double centimeters)
{
    cout << meters << " meters & " << centimeters << " cm's. " << endl;
}

为什么我的转换不起作用? 或者我做错了什么?

目标:给定以英尺和英寸为单位的长度,我想输出以米和厘米为单位的等效长度。

//Calculate function definition, insert formula here:
void calculate (double& feet, double& inches)
{
     feet = (feet * 0.3048);
  inches = (inches * 2.54);
}

最佳答案

这似乎是一种奇怪的做法,它改变了实际的输入变量。我会选择:

void calculate (double feet, double inches, double& meters, double& centimeters) {
    double all_inches = feet * 12.0 + inches;
    centimeters = all_inches * 2.54;
    meters = int (centimeters / 100.0);
    centimeters -= (meters * 100.0);
}

无论如何,即使您确实对输入和输出使用相同的变量(然后应将它们重命名为更合适的名称),转换为单一形式(英寸)仍然是最简单的) 然后转换为厘米,然后再转换回 m/cm。

在您当前的代码中,如果您传入 1ft,0in,您将返回 0.3048m,0cm,而不是更正确的 30.48cm。通过使用此答案中的代码,它将首先转换为 12.0 英寸,然后从那里转换为 30.48cm,然后转换为 0m,30.48cm。

同样,四英尺半(4ft,6in)将首先转换为 54 英寸,然后转换为 137.16cm,然后转换为 1m,37.16cm。

关于C++ 转换不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2127015/

相关文章:

c++ - 无堆栈协程与有堆栈协程有何不同?

c++ - 等待所有线程完成一项工作然后再做另一项

c++ - 将指针分配添加到 vector 后删除它

c++ - STL 和 Hana 元组之间的转换

c++ - 模板类型的引用是什么意思?

C++ 音频输出

c++ - 模板成员函数调用—— "error: expected primary-expression before ' int'”

c++ - 智能感知 : no instance of overloaded function "sqrt" matches the argument list argument types are: (double *)

c++ - 从帧缓冲区 GLSL 读取到 OpenCV

c++ - 是否有可能我有一个类的前向声明,而不是在头文件中使它们成为引用或指针