【问题标题】:Increments of 0.2 does not abide by the loop condition?0.2的增量不遵守循环条件?
【发布时间】:2019-05-10 02:43:12
【问题描述】:

我们有关于循环的作业,它显示两个计算并通过输入的 i 增加一个变量。这些代码运行并且一切正常,直到我输入a=1, b=3 i=0.2,发生的情况是它不会到达3,即使while 条件是a<=b。只有a=1, b=2, and i=0.2 时才有效

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double inputI(double i){
    for(i=0;i<=0;cin>>i){
        cout<<"i must be greater than 0"<<endl;
        cout<<"Input i: ";
    }
    return i;
}

double compX(double s, double b){
    double x;
    x = s/cbrt(b)+2*pow(s,2);
    return x;
}

double compY(double s, double x){
    double y;
    y = (x+s/x)+3*s;
    return y;
}

void display(double x, double y,double a){
    cout<<fixed<<setprecision(2)<<a<<"\t";
    cout<<fixed<<setprecision(4);
    cout<<x<<"         "<<y<<endl;
}

int main(){
    double x,y,a,b,i;

    cout<<"Input a: ";
    cin>>a;
    cout<<"Input b: ";
    cin>>b;
    i = inputI(i);
    //is there something wrong???
    do{
        x = compX(a,b);
        y = compY(a,x);
        display(x,y,a);
        a+=i;
    }while(a<=b);

}

【问题讨论】:

  • 为什么将(未初始化的)i 传递给inputI
  • 它做了什么你没想到的?
  • 请记住,doubles 是浮点数,它们并不精确。它可能看起来像 a 等于 b,但 a 可能真的是 0.99999999999997 和 b 可能是 1.000000000003 并且未通过相等性测试。有关详细信息,请参阅Is floating point math broken?

标签: c++ dev-c++


【解决方案1】:

这是双精度比较的浮点精度问题。这些似乎对我有用:

bool double_less_than(double a, double b, double epsilon = 0.001)
{
    return a < b + epsilon;
}

int main()
{
    ...
    do{
        ...
    }while(double_less_than(a, b, 0.000001));
}

【讨论】:

    【解决方案2】:

    您更正以下警告:

    警告 C4700:使用了未初始化的局部变量“i”

    例如:

    double x,y,a,b,i = 0;
    

    【讨论】:

    • 这是一个问题,但不太可能导致报告的错误。这很可能只会搞砸用户输入,因为i 以非零且可能为正的状态进入inputI。但它也可能终结世界,因为你知道,UB。
    • 是的,同意@user4581301,变量是在使用之前设置的,所以不要认为这是原因。
    • 我只是将变量初始化为零并且当前代码有效。因此,我添加到我的答案中的输出。没有神奇的代码更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多