• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

Integers

Joined
5/8/06
Messages
80
Points
16
How should I write this code so that it takes integers and outputs real numbers? The code below gives me values in integers. For example, 1/4 outputs 0.

Code:
int main()
{
       int i, j, nmat;
       double **a;
       nmat = 5;

       Init_Matrix(a, nmat);

       for (i = 0; i<nmat; ++i) {
		   for (j=0; j<nmat; ++j) {
           if (i==j) a[i][i] = 18;
		   if (i!=j) a[i][j] = abs(i-j)/(i+j+2);
		   cout << "Out " << a[i][j] << " " << " i " << i << " " << " j " << j << "\n";
		   cout << "te " << (i-j)/(i+j+2);
		   cout << "\n";
		   }
	   }
 
Sangfroid said:
How should I write this code so that it takes integers and outputs real numbers? The code below gives me values in integers. For example, 1/4 outputs 0.

Code:
int main()
{
       int i, j, nmat;
       double **a;
       nmat = 5;

       Init_Matrix(a, nmat);

       for (i = 0; i<nmat; ++i) {
		   for (j=0; j<nmat; ++j) {
           if (i==j) a[i][i] = 18;
		   if (i!=j) a[i][j] = abs(i-j)/(i+j+2);
		   cout << "Out " << a[i][j] << " " << " i " << i << " " << " j " << j << "\n";
		   cout << "te " << (i-j)/(i+j+2);
		   cout << "\n";
		   }
	   }

double (abs(i-j))/double ((i+j+2));
I am assigning a[j] to write to my output file, so all I need is to declare the numerator and denominator as doubles, right. Like the above, since that is the main line?
 
Sangfroid said:
double (abs(i-j))/double ((i+j+2));
I am assigning a[j] to write to my output file, so all I need is to declare the numerator and denominator as doubles, right. Like the above, since that is the main line?

Your numerator and denominator are still int type, you just typecast them as double to do calculation and output.
That line above should work.
 
ALRIGHT!!!! :mrgreen:
 
Andy said:
Sangfroid said:
double (abs(i-j))/double ((i+j+2));
I am assigning a[j] to write to my output file, so all I need is to declare the numerator and denominator as doubles, right. Like the above, since that is the main line?

Your numerator and denominator are still int type, you just typecast them as double to do calculation and output.
That line above should work.


You should use the new typecast operator and IIRC, you should only typecase the denominator:

Code:
abs(i-j)/static_cast<double>((i+j+2));
 
Why only the denominator?
 
Back
Top