C++ 程序在用户输入后停止

1 c++ user-input early-stopping

#include "util.h"
#include <cmath>

double celsius(double t)
{
    double C = (t-32) * 5/9;
    C = round(C);
    return C;
}

double fahrenheit(double t)
{
    double F = t * 9/5 + 32;
    F = round(F);
    return F;
}

double round(double num)
{
    double rounded = round(num);
    return rounded;
}

int main()
{
    double temp = readDouble("Please enter a temperature: ");
    string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: ");
    if(type == "C")
    {
        double convertedTemp = celsius(temp);
        cout << temp << " degrees Celsius is " << convertedTemp << " degrees Farenheit";
    }
    else if(type == "F")
    {
        double convertedTemp = fahrenheit(temp);
        cout << temp << " degrees Fahrenheit is " << convertedTemp << " degrees Celsius"; 
    }
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是我编写的一个程序,用于将华氏温度转换为摄氏度,反之亦然。由于某种原因,程序在用户输入 C 或 F 后立即停止运行,而没有运行 if 语句。

我在整个过程中都放入了 print 语句,看看它是否正在运行它们,只是没有打印任何内容,但似乎它只是在“string type = readLine(“输入 C 转换为摄氏度或 F 转换为华氏度:”)之后停止; ” 我的代码有问题还是只是我运行它的网站(CodeHS)有问题?我浏览过类似的帖子,并尝试在 return 0 之前添加 system("pause") 或 cin << randomVariable ,但都不起作用。

小智 5

看来你的round()功能有问题。您有一个名为 的函数,它也与库中的函数round()同名。这可能会导致冲突。round()<cmath>

当您调用round(C)round(F)在转换函数内部时,它会递归调用您的round()函数而不是<cmath>库中的函数。这会导致堆栈溢出,并且您的程序崩溃。

  • 这也是堆栈溢出导致堆栈溢出的情况。;) (2认同)