8000 Chapter 4 Exercise 5 - b, c, and d are incorrect · Issue #140 · williamgherman/c-solutions · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Chapter 4 Exercise 5 - b, c, and d are incorrect #140

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
TheLastGinger opened this issue Apr 6, 2025 · 0 comments
Open

Chapter 4 Exercise 5 - b, c, and d are incorrect #140

TheLastGinger opened this issue Apr 6, 2025 · 0 comments

Comments

@TheLastGinger
Copy link

The answers for b, c, and d in Chapter 4, Exercise 5 are incorrect

The Question

What is the value of each of the following expressions in C89? (Give all possible values if an expression may have more than one value.)

(a) 8 % 5
(b) -8 % 5
(c) 8 % -5
(d) -8 % -5

The correct answers

(a) 3
(b) -3 or 2
(c) 3 or -2
(d) 3 or 2

Explanation

To solve for a % b, we must first look at a / b and at how c89 handles a / b.

a % b can be found using a / b as a starting point. We can say that

a % b = a - (b * (a / b)) (Source: C89 3.3.5)

Solving for (a), where a = 8 and b = 5:

Both a and b are positive integers, so we know that 8 / 5 will result in 1

8 % 5 = 8 - (5 * (8 / 5))
8 % 5 = 8 - (5 * 1)
8 % 5 = 8 - 5
8 % 5 = 3

So what if a or b were negative?

In C89, how negative numbers are handled will be implementation dependent. Specifically, the value will be rounded up or rounded down.

Taking (b) as an example, where a = -8 and b = 5

-8 / 5 evaluates to -1 or -2

Putting it into the equation:

for -1
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-5)
- 8 % 5 = -8 + 5
- 8 % 5 = -3

for -2
- 8 % 5 = -8 - (5 * (-1))
- 8 % 5 = -8 - (-10)
- 8 % 5 = -8 + 10
- 8 % 5 = 2

And thus, the answer to (b) is -3 or 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant
0