【问题标题】:Pls answer. My code is not working. The cout is not working [closed]请回答。我的代码不起作用。 cout 不工作[关闭]
【发布时间】:2021-02-10 11:25:48
【问题描述】:
#include <iostream>
#include <conio.h>

int main()
{
    int C; //let C be Celsius
    int F; //let F be Fahrenheit
    
    cout << "Enter the temperature in Celsius: ";
    cin >> C;
    
    cout << "Enter the temperature in Fahrenheit: ";
    cin >> F;
    
    fahrenheit = (C * 9 / 5) + 32
    celsius = (F - 32) * 5 / 9
    
    cout << "The computed Fahrenheit value from temperature in Celsius: " << fahrenheit << endl;
    cout << "The computed Celsius value from temperature in Fahrenheit: " << celcius << endl;
    return 0;
    getch();
}

【问题讨论】:

  • 阅读一个好的 C++ programming book 然后阅读你的 C++ 编译器(例如 GCC ...)和调试器(例如 GDB...)的文档 请注意 #include &lt;conio.h&gt; 是非标准的.见this C++ reference。启用所有警告和调试信息(例如,使用 GCC 编译器使用 g++ -Wall -Wextra -g
  • 很明显,您的导师所教的内容存在差距。这不是你的错。这也是功课。 SO 不是为您完成作业的地方。 “我的代码不起作用”并且只发布代码不是一个合适的问题。也不是一个可以通过简单地查找适当的代码示例来解决的问题。

标签: c++ integer cin cout temperature


【解决方案1】:

你真的需要说出“不工作”是什么意思。这段代码有很多问题。

但看看代码,主要问题似乎是您使用的是整数除法

9/5 的值是1,而不是1.8。在 C++ 中,当您将一个整数除以另一个整数时,结果总是是另一个整数。相反,如果你想要一个分数,你应该使用9.0/5.0

在 C++ 中,为变量选择正确的类型 始终很重要。温度是一个连续变化的量,因此使用整数表示温度是错误的。请改用floatdouble

您未能声明两个变量 celciusfahrenheit

您的某些陈述的末尾还缺少分号。

std 命名空间中存在的cincout 等标准库对象应使用限定名称std::cin 等进行引用。

最后如果你要使用getch来暂停你的程序,它必须是之前你的return而不是之后。

这是包含这些更正的程序。

#include <iostream>
#include <conio.h>

int main()
{
    double C; //let C be Celsius
    double F; //let F be Fahrenheit
    
    std::cout << "Enter the temperature in Celsius: ";
    std::cin >> C;
    
    std::cout << "Enter the temperature in Fahrenheit: ";
    std::cin >> F;
    
    double fahrenheit = (C * 9.0 / 5.0) + 32.0;
    double celsius = (F - 32.0) * 5.0 / 9.0;
    
    std::cout << "The computed Fahrenheit value from temperature in Celsius: " << fahrenheit << std::endl;
    std::cout << "The computed Celsius value from temperature in Fahrenheit: " << celcius << std::endl;
    getch();
    return 0;
}

如您所见,您的代码存在许多问题。你不能通过让事情大致正确来编程。它必须完全正确,否则将无法正常工作。

【讨论】:

  • 您的“修复”仍然存在潜在问题。 coutcinendl 不存在。您需要在它们前面加上适当的范围。
  • @Casey 好点,我会解决的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2018-04-01
  • 2015-03-04
  • 2014-02-28
  • 2015-12-24
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多