I have a struct containing three numbers: number1, number2, number3. Then, I want to perform division operators on them: (number1)/(number2 number3).
typedef struct {
int number1;
int number2;
int number3;
double ratio;
} table;
I tried to divide them like this:
for(int a = 0; a < 5; a )
{
for(int b = 0; b < 3; b )
{
table[a][b].ratio = ((table[a][b].number1)/(table[a][b].number2 data[a][b].number3));
}
}
Should I divide structures using a repeated subtraction of dividend and divisor till the dividend becomes less than the divisor? Or is there any other approaches? I need to get double values, for example:
table[0][0].number1 = 1;
table[0][0].number2 = 2;
table[0][0].num3 = 3;
Then,
table[0][0].ration = 1/5=0.2
CodePudding user response:
Your code seems right. All that's missing is a casting to double before you do your division, something like:
table[a][b].ratio = ((double)(table[a][b].number1)) /
(table[a][b].number2 data[a][b].number3);
If one of the operands is a floating point number in C, the division becomes a floating point division.
CodePudding user response:
You need to change the division so that the operands are floating point. It's generally not recommended to mix integers and floating point operands in the same expression without explicit casts. The inner for
loop body should be rewritten as:
int sum = table[a][b].number2 data[a][b].number3;
table[a][b].ratio = (double)table[a][b].number1 / (double)sum;