gpt4 book ai didi

c++ - 这个输入中的 float 和 double 有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:12 25 4
gpt4 key购买 nike

我有两个输入,唯一的区别是我在第二个输入中用“float”替换了“double”。但是,第一个可以按预期运行但第二个不能。第二个不是以0.1的输入结束。有人对此有一些想法吗?非常感谢!

第一个输入:

#include <iostream>

using namespace std;

int main()
{
double input;
input = 0;
double sum = 0;
cout << "Please enter a series numbers and end with 0.1: ";
cin >> input;
while (input != 0.1)
{
sum += input;
cout << "The cumulative sum is: " << sum << endl;
cin >> input;
}
return 0;
}


Please enter a series numbers and end with 0.1: 1 2 3 0.1
The cumulative sum is: 1
The cumulative sum is: 3
The cumulative sum is: 6

第二个输入:

#include <iostream>
using namespace std;

int main()
{
float input;
input = 0;
float sum = 0;
cout << "Please enter a series numbers and end with 0.1: ";
cin >> input;
while (input != 0.1)
{
sum += input;
cout << "The cumulative sum is: " << sum << endl;
cin >> input;
}
return 0;
}


Please enter a series numbers and end with 0.1: 1 2 3 0.1
The cumulative sum is: 1
The cumulative sum is: 3
The cumulative sum is: 6
The cumulative sum is: 6.1

最佳答案

条件 (input != 0.1) 中的

0.1 是最接近有理数 1/10 的 double。最接近此有理数的 float 0.1f 表示不同的值,不会使此条件为真。

如果你想在你的程序中使用float,使用(input != 0.1f)作为相应的条件。

关于c++ - 这个输入中的 float 和 double 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210442/

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