function returning different types

inighthawki

Newcomer
Joined
Nov 29, 2005
Messages
14
Im creating a set of useful functions, and one of them is to do the quadratic formula; however, if the result answer is imaginary, it returns NaN because it cant return imaginary numbers. My function normally returns a Double value, but what if u want it to return a string so it can display imaginary numbers? To do so i can code it to display (-B/2A) +- Sqrt(B^2 - 4AC) & "i" - simply put, but this is a string, and the function is a double. How can i make it so i can return both values? or do i have to make them all come back as strings?
 
The simple fact is that C++ and .Net mathematical functions only work with real numbers. If you want to deal with imaginary numbers you either need to write your own functions and classes to deal with them or find a third party library. The first option isn't as bad as it sounds.

If I were you I would create a ComplexNumber class. You will need to add to this, obvisously. Also, this is a managed class, but there isn't really any need for this if you prefer otherwise (the conversion is easy enough: remove the "ref" keywork, replace hats (^) with stars (*), and use standard C++ functions).

ComplexNumber.h
Code:
#pragma once

ref class ComplexNumber
{
public:
	[Color=green]// Constructors[/color]
	ComplexNumber(void);
	ComplexNumber(double, double);

	[Color=green]// Actual values[/color]
	double real;
	double imaginary;
	
	[Color=green]// Mathematical functions[/color]
	static ComplexNumber^ Distance(ComplexNumber^ a, ComplexNumber^ b);
	ComplexNumber^ Negate();
	ComplexNumber^ Add(ComplexNumber^ a);

	[Color=green]// It is always handy to be able to show the user the value 
	// so we will want a method to return a string representation.[/color]
	virtual System::String^ ToString() override ;
};
ComplexNumber.cpp
Code:
#include "StdAfx.h"
#include "ComplexNumber.h"

ComplexNumber::ComplexNumber(void)
{
}

ComplexNumber::ComplexNumber(double realValue, double imaginaryValue){
	real = realValue;
	imaginary = imaginaryValue;

}

ComplexNumber^ ComplexNumber::Distance(ComplexNumber^ a, ComplexNumber^ b){
	ComplexNumber^ result = gcnew ComplexNumber();
	result->real = System::Math::Sqrt(a->real * a->real - a->imaginary + b->real * b->real - b->imaginary);
	result->imaginary = 0;
	return result;
}

ComplexNumber^ ComplexNumber::Negate (){
	return gcnew ComplexNumber(-real, -imaginary);
}

ComplexNumber^ ComplexNumber::Add(ComplexNumber^ a){
	ComplexNumber^ result = gcnew ComplexNumber();
	result->real = a->real + real;
	result->imaginary = a->imaginary + imaginary;
	return result;
}

System::String^ ComplexNumber::ToString(){
	return System::String::Concat(real.ToString(), " ", imaginary.ToString(), "i");
}
 
Back
Top