C++ Programming GalleryThe Programming Challenge

Challenge 8 – Evaluate a math function in one line of code in C++

Difficulty x10
x3

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: 23-X-2000
Created by: José Luis De la Cruz
Challenge winner: RiMS

The problem is simple, just enter a number “x”, then evaluate “f(x)” and display this result on the screen. Where the function
f(x) is defined as follows:

f(x) = { 2sen(x/2)(cos(x/2))^2 , x<0
         1/4*sen(2*x)*sec(x/2) , 0<=x<2
         exp(x)*tan(x/2)       , x>2    }

Note: ^2 means squared.

To achieve the above, I attach an incomplete program. In this program you can see some dotted lines ( ……. ) that must be completed with code.

Problem Conditions

These conditions must be respected, otherwise your solution will be disqualified.

  1. Do not modify the code that is already written, only the dotted lines must be completed.
  2. You cannot declare more functions, the only function declared in the program must be:
    double f(double x).
  3. You cannot use the if statement.
  4. In the dotted lines that appear inside the function: double f(double x) you cannot use any type of conditional statement or operator.
  5. The evaluation of the function f(x) must be done only within the function:
    double f(double x) , nowhere else in the program.

Source Code

#include <iostream>
using std::cout;
using std::cin;

.......

double f( double x )
{
        return .......
}

int main() {
	double x;
	cout << "\Enter X: ";
	cin >> x;

        .......

	cout << "\nResult: f( "<< x <<" ): " << f(x);
	
	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

Solution

Leave a Reply

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

Back to top button