Code Returns A Value of Zero For Simple Variable

Feb 8, 2012 at 3:30am
I have defined a variable dX = (b - a)/N, where a = 0, b = 3, and N = 15; however, when I print dX, it always gives me a value of zero which makes no sense. I'm not sure what in my code is causing this to occur. I've tried using different allocations for the variables, but nothing seems to work. I even tried putting it inside and outside int main(), but that didn't do anything either. Does anyone have a suggestion?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <fstream>
#include <cmath>

using namespace std;

const int N = 15;
int a = 0;
int b = 3;
double dX = (b - a)/N;
double x [N];

int main ()
{
    x[0] = a;
    for (int i = 1; i < N; i++)
    {
        x[i] = x[i-1] + dX;
    }
    cout << dX << endl;
    return 0;
}
Last edited on Feb 8, 2012 at 3:30am
Feb 8, 2012 at 3:40am
a, b and N are integers so the result of (b - a)/N will also be an integer. You could change one of the variables to a double or use a cast on one of the sides of /.
double dX = static_cast<double>(b - a) / N;
Last edited on Feb 8, 2012 at 3:40am
Feb 8, 2012 at 3:45am
Sure try Peter's
Last edited on Feb 8, 2012 at 3:53am
Feb 8, 2012 at 3:46am
Thank you for that. I did not know that C++ won't accept two different data types. In the long run, is it generally better, storage wise, to use a cast or use double for all my values?
Feb 8, 2012 at 4:15am
Use the type that makes more sense. N should be an integer because that is what it is, and you can't use it to specify the size of the array if it isn't an integer. a and b are probably better as doubles.
Last edited on Feb 8, 2012 at 4:15am
Feb 8, 2012 at 4:19am
C++ accepts two types, but it'll cast for you and won't care if you lose data or not. Computers have no idea how to add 3 to 4.5678. It has to make them of the same type.
Feb 8, 2012 at 4:29am
C++ accepts two types, but it'll cast for you and won't care if you lose data or not. Computers have no idea how to add 3 to 4.5678. It has to make them of the same type.


I think I'm so used to working with MATLAB that I've started to take for granted the basic operations of a computer. :-)
Feb 8, 2012 at 4:36am
Haha no worries :D Just things you should keep in mind. On a semi side note, most computers anymore have a separate processor entirely for floating point arithmetic, which you should see is another reason why a computer can't add integers and floating points
Feb 8, 2012 at 9:10am
Actually what does your program do????

Is it for integration or something?????
Topic archived. No new replies allowed.