1

I would be grateful if somebody could help me with this question.

A C program contains the following declarations and initial assignments.

int i = 8,  j = 5;
float x = 0.005, y = - 0.01;
char c = 'c',  d = 'd';

Determine the value of the following expression using values assigned to the variables for the expression:

(i - 3 * j) % ( c + 2 *d)/ (x - y )

I tried this manually first:

( i- 3 * j) % ( c + 2 *d ) / ( x - y)
( 8 - 3*5) % ( 99 + 2 * 100 ) / ( 0.005 - (-0.01) )
( -7 ) % ( 299 ) / (  0.015 )

Keeping precedence and associativity in mind, I used the mod operator first:

( 292 ) / (  0.015 )

Which gave the answer 19466.66.

This does not match with the answer given in the book or when I used this in codeblocks, both of which gave the answer as - 466.6667

The codeblocks program is as below

#include <stdio.h> 
#include <stdlib.h> 
 
int main() 
{ 
    int i = 8,j = 5, c = 'c',d = 'd'; 
    float x = 0.005, y = -0.01, a = 0.0; // a is the float variable to which the value is assigned
    a = (i-3*j)%(c+2*d)/(x-y); 
    printf("%f\n",a); 
    return 0; 
}

2 Answers2

1

The crux of this is the integer part before division:

(i-3*j)%(c+2*d)

Where that evaluates to:

(8-3*5) % (99 + 2 * 100)
(8-15) % (99 + 200)
-7 % 299

So now it depends on what definition of modulo is being used by C, as there are several it could be. C interprets this as -7 while other languages always map to the 0 to 298 range.

The rest is just simple division.

tadman
  • 208,517
  • 23
  • 234
  • 262
-2

You have to use division at the end (and once) of your calculation to keep the precision.

With division, you can lose precision. See the butterfly effect Wikipedia page why it can make huge differences.

You can work with fractions and only divide when you print them.

artit91
  • 83
  • 7
  • 3
    If this is butterfly effect, then the butterfly involved is [Mothra](https://en.wikipedia.org/wiki/Mothra). – tadman Mar 31 '21 at 05:58