C/C++ Calculation in C++: B-C && (B-A) /C - Which Answer is Right?

  • Thread starter Thread starter ccky
  • Start date Start date
  • Tags Tags
    C++ Calculation
AI Thread Summary
The discussion centers on a C++ calculation involving the expression B-C && (B-A)/C with variable assignments A=2, B=3, and C=4. There is confusion about the result of the expression, with one participant believing the answer is 0 because the first part is negative, while others argue it should be 1 since -1 does not equate to false. The correct interpretation clarifies that in C++, only 0 represents false, and the expression evaluates to false (0). The breakdown shows that B-C results in -1 and (B-A)/C results in 0, leading to the final evaluation of -1 && 0, which is true && false, ultimately yielding a result of false (0).
ccky
Messages
15
Reaction score
0
I am doing my homework regarding calculation in c++.
I am confused by the below question.
Int A=2 B=3 C=4
B-C && (B-A) /C
I think the answer is 0 because the first part is negative.
But,my friends say the answer is 1 because -1 not mean false.
I want to ask which answer is right?
Thanks.
 
Technology news on Phys.org
Your friend is right - -1 doesn't mean false. 0 and only 0 means false.
 
  • Like
Likes 1 person
You and your friend are both incorrect. You could easily check this by running it through a C++ compiler.

In C++, there is implicit conversion from ints to bools. && has pretty low precedence, so first the following expressions are evaluated: B - C is 3 - 4 = -1, and (B - A) / C is 1 / 4 = 0 (in integer division).
So the resulting expression is -1 && 0 which is equivalent to true && false, hence the result you get is false (0).
 
Last edited:
  • Like
Likes 1 person
Ah, I referred just to the small part of the post, I have not actually bothered to evaluate whole expression :shy:
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top