简体   繁体   English

循环帮助。 在不应有的情况下终止。 C ++

[英]for loop help. Terminates when it isnt supposed to. c++

I'm new to stackoverflow, but i did try to look for an answer and could not find it. 我是stackoverflow的新手,但我确实尝试寻找答案,但找不到。 I also can't seem to figure it out myself. 我自己也似乎无法弄清楚。 So for a school C++ project, we need to find the area under a curve. 因此,对于学校C ++项目,我们需要找到曲线下的面积。 I have all the formulas hardcoded in, so don't worry about that. 我已经将所有公式都硬编码了,所以不用担心。 And so the program is supposed to give a higher precision answer with a higher value for (n). 因此,该程序应该为(n)提供更高的精度和更高的值。 But it seems that when I put a value for (n) thats higher than (b), the program just loops a 0 and does not terminate. 但是似乎当我将(n)的值设置为大于(b)时,该程序仅循环0并且不会终止。 Could you guys help me please. 你们能帮我吗。 Thank you. 谢谢。 Heres the code: 这是代码:

/* David */

#include <iostream>
using namespace std;

int main()
{

cout << "Please Enter Lower Limit: " << endl;
int a;
cin >> a;

cout << "Please Enter Upper Limit: " << endl;
int b;
cin >> b;

cout << "Please Enter Sub Intervals: " << endl;
int n;
cin >> n;

double Dx = (b - a) / n;
double A = 0;
double X = a;

for (X = a; X <= (b - Dx); X += Dx)
{
    A = A + (X*X*Dx);
    X = X * Dx;
    cout << A << endl;
}

cout << "The area under the curve is: " << A << endl;

return 0;
}

a , b , n are integers. abn是整数。 So the following: 因此,以下内容:

(b - a) / n

is probably 0. You can replace it with: 可能为0。您可以将其替换为:

double(b - a) / n

Since all the variables in (b - a) / n are int , you're doing integer division, which discards fractions in the result. 由于(b - a) / n中的所有变量均为int ,因此您正在执行整数除法,这将丢弃结果中的分数。 Assigning to a double doesn't change this. 分配给double不会改变这一点。

You should convert at least one of the variables to double so that you'll get a floating point result with the fractions retained: 您应该将至少一个变量转换为double以便获得保留分数的浮点结果:

double Dx = (b - a) / (double)n;

The other answers are correct. 其他答案是正确的。 Your problem is probably integer division. 您的问题可能是整数除法。 You have to cast on of the operands to double. 您必须将操作数转换为两倍。

But you should use static_cast<> instead of C-style casts . 但是您应该使用static_cast <>而不是C风格的强制类型转换 Namely use 即使用

static_cast<double>(b - a) / n

instead of double(b - a) / n or ((double) (b - a)) / n . 而不是double(b - a) / n((double) (b - a)) / n

You are performing integer division. 您正在执行整数除法。 Integer division will only return whole numbers by cutting off the decimal: 整数除法将仅通过截断小数来返回整数:

3/2 == 1 //Because 1.5 will get cut to 1
3/3 == 1
3/4 == 0 //Because 0.5 will get cut to 0

You need to have at least one of the two values on the left or right of the "/" be a decimal type. 您需要至少在“ /”左侧或右侧的两个值之一为十进制类型。

3 / 2.0f == 1.5f
3.0f / 2 == 1.5f
3.0f / 2.0f == 1.5f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM