Quadratic Equation solver in C++ – revision 2

Posted on Updated on

i modified my code for the quadratic equation solver so that calculations would look “only slightly” easier to read.. just incase future me wants to punch past me if this looks bad or worse than the original:

From what I understand about templates, if we have 2 data type variables (a double and an int) and we can’t calculate both types in the same function we would have to write 2. But instead of doing that we can generalize 1 function to accept both parameter types so we don’t need to have duplicates.. which was the idea I had when I wrote this:

In my header file:

template<typename T> // は?
T calculateAC(T a, T c);

And in my implementation I modified the code in my previous post to look like this:

/*
 * 4*(a*c)
 * 入力されたデータは一般化されたのでdoubleかintでも計算できる
 */
template<typename T>
T firstSolution::calculateAC(T a, T c) {
	return a*c;
}

/*
 * 平方根の計算
 */
void firstSolution::calculateSquareRoot(int a, int b, int c) {
	int ac = this->calculateAC(a, c);
	quadratic_formula = sqrt((b*b) + (4 * ac));			// ax2 + bx + c = 0
	result[0] = (((b * -1) + quadratic_formula) / 2);	// 二次方程式(+)
	result[1] = (((b * -1) - quadratic_formula) / 2);   // 二次方程式(ー)
}

/*
 * 処理された回答を取得
 */
void firstSolution::getValues() {
	for(int i = 0; i < 2; i++) {
		cout << "x = [ " <<  result[i] << " ]\n";
	}
}

The calculation for a=1, b=3 and c=4 will output x=-4, x=1 which … is the right answer for 1 possible solution. But, to calculate ALL possible solutions I need to somehow fix the source … I’ll come back to this later.

benjamin.lo% g++ firstSolution.cpp
benjamin.lo% ./a.out
aの値を入力してください:
1
bの値を入力してください:
3
cの値を入力してください:
4
aの値を [ 1 ]として入力されました。
bの値を [ 3 ]として入力されました。
cの値を [ 4 ]として入力されました。
x = [ 1 ]
x = [ -4 ]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s