我试图创建一个简单的计算器,我在使用添加时遇到了问题。我创建了一个添加函数,每当我传入两个值时,我得到一个不同的答案。例如,当我添加4,5时我希望得到9但我得到的答案是 0029144C 。我仍然是初学者,所以起初我不确定是否使用类型bool进行添加功能会影响我的结果,但我将其改为输入float并仍然得到相同的结果(如果有人问)。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void SimCalcMenu();
void additionSign();
bool makeSum(float num1, float num2);
int main() {
float firstNum, SecondNum;
char operationLetter;
SimCalcMenu();
cout << " Please Select an Operation You Would Like to Perform ";
cin >> operationLetter;
if (operationLetter == 'a' || operationLetter == 'A')
{
additionSign();
cout << " Enter the First Number : ";
cin >> firstNum;
cout << " Enter the Second Number: ";
cin >> SecondNum;
makeSum(firstNum, SecondNum);
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum << endl;
}
else
{
cout << " Error ";
}
return 0;
}
void SimCalcMenu() {
cout << "------------------------------------------------------------------------------" << endl;
cout << " WELCOME TO SIM CALCULATOR " << endl;
cout << "------------------------------------------------------------------------------" << endl;
cout << endl;
cout << " Please Select an Operation : " << endl;
cout << " A.) Addition " << endl;
cout << " B.) Subtraction " << endl;
cout << " C.) Multiplication " << endl;
cout << " D.) Division " << endl;
cout << " E.) Roots ( Only Positive Number)" << endl;
cout << " F.) Power ( Only Positive Number " << endl;
cout << " G.) Percentage " << endl;
cout << " H.) Display functions execution " << endl;
cout << " I.) Quit " << endl;
cout << "------------------------------------------------------------------------------" << endl;
}
void additionSign() {
cout << "------------------------------------------------------------------------------" << endl;
cout << " ADDITION " << endl;
cout << "------------------------------------------------------------------------------" << endl;
}
bool makeSum(float num1, float num2) {
float totSum;
totSum = num1 + num2;
return totSum;
}
答案 0 :(得分:6)
makeSum()
应该返回float,因为你要返回两个浮点数的总和。
您无法获得正确的结果,因为您正在打印makeSum
,这是该函数的地址。您想要打印makeSum(firstNum, SecondNum)
。
答案 1 :(得分:4)
这一行
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum << endl;
IS&#39;打印&#39; &#39; makesum&#39;,makesum是一个函数,因此它打印makeum的地址
你需要
cout << " The Sum of " << firstNum << " and " << SecondNum << " is :" << makeSum(firstNum, SecondNum) << endl;
现在至少会打印makesum
的结果。正如其他人指出函数是错误的(它返回一个bool)。
应该是
float makeSum(float num1, float num2) {
float totSum;
totSum = num1 + num2;
return totSum;
}