简体   繁体   中英

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. 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. 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). 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. 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. So the following:

(b - a) / n

is probably 0. You can replace it with:

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. Assigning to a double doesn't change this.

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 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 . Namely use

static_cast<double>(b - a) / n

instead of double(b - a) / n or ((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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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