gpt4 book ai didi

c++ - 已编译的 C++ 应用程序提供随机浮点值

转载 作者:行者123 更新时间:2023-11-28 00:05:23 25 4
gpt4 key购买 nike

在编译控制台应用程序并输入错误数据后,它在请求数字时给出奇怪的输出值,如 2.0434e-006。这是代码:

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

int main() {
using namespace std;
float l,w,h;
float s;
cout << "\nCalculating surface area of the parallelepiped\n";
cout << "Enter the raw data:\n";
cout << "Length (cm) -> ";
cin >> l;
cout << "Width (cm) -> ";
cin >> w;
cout << "Height (cm) -> ";
cin >> h;
s = (l*w + l*h + w*h)*2;
cout << "Surface area: " << s << " sq. cm\n";
cout << "\n\nPress any key...";
getch();
}

我听说过一些关于 IEEE 754 浮点错误的消息,但即使是这些信息也不能确定我的知识。

最佳答案

未初始化的非静态局部变量的值是不确定的。

检查输入是否成功并处理错误。

#include <iostream>

int main() {
using namespace std;
float l,w,h;
float s;
cout << "\nCalculating surface area of the parallelepiped\n";
cout << "Enter the raw data:\n";
cout << "Length (cm) -> ";
if (!(cin >> l)) {
cout << "input error\n";
return 1;
}
cout << "Width (cm) -> ";
if (!(cin >> w)) {
cout << "input error\n";
return 1;
}
cout << "Height (cm) -> ";
if (!(cin >> h)) {
cout << "input error\n";
return 1;
}
s = (l*w + l*h + w*h)*2;
cout << "Surface area: " << s << " sq. cm\n";
cout << "\n\nPress any key...";
}

关于c++ - 已编译的 C++ 应用程序提供随机浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35965853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com