PDA

View Full Version : Integers


Peik Looi
10-17-2006, 04:28 PM
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.

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";
}
}

Andy
10-17-2006, 04:42 PM
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.
One word: typecasting
cout <<double(1)/double(4);

Peik Looi
10-17-2006, 04:45 PM
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.

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[i][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?

Andy
10-17-2006, 05:01 PM
double (abs(i-j))/double ((i+j+2));
I am assigning a[i][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.

Peik Looi
10-17-2006, 05:08 PM
ALRIGHT!!!! :mrgreen:

alain
10-17-2006, 05:21 PM
double (abs(i-j))/double ((i+j+2));
I am assigning a[i][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:

abs(i-j)/static_cast<double>((i+j+2));

Peik Looi
10-18-2006, 12:17 AM
Why only the denominator?