C++ Programming GalleryThe Programming Challenge

Challenge 0 – Why doesn’t the operation give the correct value? in C++

Difficulty x10
x5

This Challenge was proposed for the now defunct C/C++ programming list CWORLD in 1999.
The source code of the challenge has been updated to modern C++, but maintaining the essence of the challenge, which its original author wanted to transmit.

Date: 1-VIII-2000
Created by: David A. Capello
Challenge winner: Francisco Manuel Martín Delfa

This is very easy. Why doesn’t the operation give the correct value? Can you fix the code?

NOTE: I learned this from a C/C++ book, which warned about this error.

Source Code

#include <iostream>


#define ADD(x,y)    x + y
#define SUB(x,y)    x - y
#define MUL(x,y)    x * y
#define DIV(x,y)    x / y


int main(void)
{
	double x, y;
	x = 5;
	y = 2;
	/* (5/2+5*2)*2 = 25 */
	std::cout << "(x/y+x*y)*2 = " << ADD(DIV(x, y), MUL(x, y)) * 2 << std::endl;
	return 0;
}

AND FINALLY I CAN ONLY SAY …. BEST OF LUCK AND MAY THE BEST CODE WIN….

If you liked this challenge remember to leave a comment in our guestbook

Solución

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button