为什么 C++数学运算接受一个字母作为输入并输出一个数字?

发布于 2025-01-14 05:26:15 字数 762 浏览 1 评论 0原文

我是 C++ 的新手,所以也许这是一个愚蠢的问题,但我编写了一个非常简单的温度转换程序。它看起来像这样:

#include <iostream>

int main() {
  
  double tempf;
  double tempc;
  
  // Ask the user
  std::cout << "Enter the temperature in Fahrenheit: ";
  std::cin >> tempf;
  
  // Conversion
  tempc = (tempf - 32) / 1.8;
  
  // Print Output  
  std::cout << "The temp is " << tempc << " degrees Celsius.\n";
  
}

当我输入整数/浮点数作为输入时,它可以编译并运行良好。然而,出于好奇,我尝试输入一封信,预计会出现错误或某种失败。相反,编译后,我得到以下输出:

$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit: abc
The temp is -17.7778 degrees Celsius.

有人能告诉我可执行文件从哪里获取输出 -17.7778 吗?这看起来像是一个任意数字,而不是数学输出。

I'm brand new to c++, so maybe this is a stupid question, but I coded a very simple temperature conversion program. It looks like this:

#include <iostream>

int main() {
  
  double tempf;
  double tempc;
  
  // Ask the user
  std::cout << "Enter the temperature in Fahrenheit: ";
  std::cin >> tempf;
  
  // Conversion
  tempc = (tempf - 32) / 1.8;
  
  // Print Output  
  std::cout << "The temp is " << tempc << " degrees Celsius.\n";
  
}

This compiles and runs fine when I enter an integer/float as an input. However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind. Instead, after compiling, I get this output:

$ g++ temperature.cpp -o temp
$ ./temp
Enter the temperature in Fahrenheit: abc
The temp is -17.7778 degrees Celsius.

Can someone tell me where the executable is getting the output -17.7778 from? This seems like an arbitrary number, not a mathematical output.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失眠症患者 2025-01-21 05:26:15

“但是,出于好奇,我尝试输入一个字母,希望得到某种错误或失败。”

默认情况下,std::cin 通过以下方式报告错误:设置必须手动检查的内部错误位。一种机制是使用 good() 成员函数来检查任何错误位。另一种是使用 bool 转换运算符,它执行相同的操作,如果没有设置错误位,它将转换为 true,否则它将转换为 false代码>.

示例:

if(!std::cin) {
    std::cout << "Input error!";
    return;
}

std::cin失败时,它将把值0赋给变量。

来自 cppreference.com

如果提取失败(例如,如果在需要数字的地方输入了字母),则将零写入值并设置失败位。

当您提供输入 "abc" 时,表达式 std::cin >>> tempf; 将无法读取任何内容,将 0 分配给 tempf 并设置一个失败位。然后,在 tempc = (tempf - 32) / 1.8; 期间计算出的值将为 (0.0 - 32) / 1.8,大约为 -17.7778 > 这是您观察到的结果。

您可以使用 exceptions 成员函数更改默认行为以在失败时引发异常。但请注意,如果项目的其他部分使用 std::cin 且不希望进行此更改,则可能会破坏其可能依赖于检查错误位的错误处理方案。

cppreference.com 提供的示例:

#include <iostream>
#include <fstream>
 
int main() 
{
    int ivalue;
    try {
        std::ifstream in("in.txt");
        in.exceptions(std::ifstream::failbit); // may throw
        in >> ivalue; // may throw
    } catch (const std::ios_base::failure& fail) {
        // handle exception here
        std::cout << fail.what() << '\n';
    }
}

"However, out of curiosity, I tried entering a letter, expecting to get an error or a failure of some kind."

By default, std::cin reports errors by setting internal error bits that must be checked manually. One mechanism is to use the good() member function to check for any error bits. Another is to use the bool conversion operator which does the same thing, it will convert to true is no error bits are set, otherwise it converts to false.

Example :

if(!std::cin) {
    std::cout << "Input error!";
    return;
}

When std::cin fails, it will assign the value 0 to the variable.

From cppreference.com :

If extraction fails (e.g. if a letter was entered where a digit is expected), zero is written to value and failbit is set.

When you provide the input "abc" the expression std::cin >> tempf; will fail to read anything, assign 0 to tempf and set a fail bit. Then, during tempc = (tempf - 32) / 1.8; the value calculated will be (0.0 - 32) / 1.8 which is approximately -17.7778 which is the result you observe.

You can change the default behavior to throw an exception on failure by using the exceptions member function. But beware that if other parts of your project use std::cin and don't expect this change it can disrupt their error handling scheme which may rely on checking error bits.

The example provided by cppreference.com for this example :

#include <iostream>
#include <fstream>
 
int main() 
{
    int ivalue;
    try {
        std::ifstream in("in.txt");
        in.exceptions(std::ifstream::failbit); // may throw
        in >> ivalue; // may throw
    } catch (const std::ios_base::failure& fail) {
        // handle exception here
        std::cout << fail.what() << '\n';
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文