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; } 
8
  • Try not to use line numbers in your code. We'll just have to delete that, tediously, if we want to run it and test. Commented Mar 31, 2021 at 5:38
  • This is an exercise in using operators and ASCII values given in the book. Thanks for the edit. Commented Mar 31, 2021 at 5:48
  • You have an arithmetic error: 0.005 - 0.01 == -0.005, not -0.015. Commented Mar 31, 2021 at 5:52
  • Also your code has y = -0.01 but the problem has y = 0.01; which is it supposed to be? Finally (-7) % 299 is not 292 but -7. Commented Mar 31, 2021 at 5:58
  • In the code it's y = -0.01 not positive 0.01. Commented Mar 31, 2021 at 5:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.