【发布时间】: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?。