gpt4 book ai didi

c++ - C++中双变量的逼近

转载 作者:行者123 更新时间:2023-11-28 04:47:36 28 4
gpt4 key购买 nike

我正在尝试运行这个程序,在其中插入两个 double 值,然后返回两个数字中哪个更大,如果两个 double 的值相同,则返回一条消息“数字相等” , 如果两个数字之间的差异小于 1/10.000.000,则显示一条消息“数字几乎相等”。

我写的代码是这样的:

    #include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

double square(double x)
{
return x * x;
}

int main() {
double number;
double number2;
while (cin >> number, cin >> number2) {
if (number == '|' || number2 == '|') break;
else {
cout << number << " " << number2 << endl;
if (number > number2) cout << number << " is bigger than " << number2 << endl;
if (number < number2) cout << number2 << " is bigger than " << number << endl;
double difference = number - number2;
if (difference > - 1/10000000 && difference < 0) cout << "the numbers are almost equal" << endl;
if (difference < 1 / 10000000 && difference > 0) cout << "the numbers are almost equal" << endl;
if (number == number2) cout << "the numbers are equal" << endl;
}

}
}

当我运行这个程序并插入两个差值小于 1/10.000.000 的数字时,程序应该返回“数字几乎相等”,但事实并非如此。

如果我插入“1”和“1.0000000000001”,这就是它返回的内容(当我运行程序并插入两个数字时):

    "1 1.0000000000001

1 1

1 is bigger than 1"

我不明白为什么程序将我插入的两个数字视为 1,并返回“1”和“1”作为值。

它也应该给出“数字几乎相等”的返回,因为我写道:

     if (difference > - 1/10000000 && difference < 0) cout << "the numbers are almost equal" << endl;
if (difference < 1 / 10000000 && difference > 0) cout << "the numbers are almost equal" << endl;

但事实并非如此。

当我插入两个相差小于 1/10.000.000 的 double 值(例如“1”和“1.0000000000001”)时,如何让程序返回“数字几乎相等”?

最佳答案

当您尝试打印这些 double 值时,cout 会对其进行四舍五入。参见 here

至于您的代码,整数除法 (1/10000000) 将始终返回一个整数,因此您需要执行 double 或十进制值 (1.0/10000000.0) 的除法

这是一个工作代码,对逻辑做了一些小改动

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

double square(double x)
{
return x * x;
}

int main() {
double number;
double number2;
while (cin >> number, cin >> number2) {
if (number == '|' || number2 == '|') break;
else {
cout.precision(15);
cout << number << " " << number2 << endl;
double difference = number - number2;
if (difference > - 1/10000000.0 && difference < 0) cout << "the numbers are almost equal" << endl;
else if (difference < 1/10000000.0 && difference > 0) cout << "the numbers are almost equal" << endl;
else if (number == number2) cout << "the numbers are equal" << endl;
else if (number > number2) cout << number << " is bigger than " << number2 << endl;
else if (number < number2) cout << number2 << " is bigger than " << number << endl;
}

}
}

关于c++ - C++中双变量的逼近,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48961946/

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