【发布时间】:2017-02-19 11:52:51
【问题描述】:
为什么当我输入 0.1 作为步长时,我的代码对于作为输出的 x 值只上升到 2.4?如果我输入像 .01 或 .001 这样的值,它会上升到 2.5。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double step;
double x0 = 1.0;
double y0 = 1.0;
double diffY;
std::cout << std::fixed;
std::cout << std::setprecision(2);
cout << "Enter step value: ";
cin >> step;
while (x0 <= 2.5 ) {
diffY = x0 + ((3*y0) / x0);
cout << x0 << " " << y0 << "\n";
x0+=step;
y0+=step*(diffY);
}
return 0; //initially defined the main function to return an int
}
谢谢!
【问题讨论】:
-
您应该使用基于整数的限制进行循环,并在循环内按比例缩小值。否则,您的循环可能会运行不同的次数,具体取决于编译器、编译器选项等。
标签: c++ approximation