简单计算器C++
Simple Calculator C++
我为家庭作业编写了这个程序。我没有得到正确的输出。有人告诉我,这是因为我不会在两组计算之间重置PreviousResult,但我不知道如何做到这一点。输出应为:
请输入文件名:calc.txt
计算1的结果是:26
计算2的结果是:2
计算3的结果是:0
相反,我得到了4次计算,其中计算3=1,4=0
calc.txt文件为:
3加5 4添加_修订4mul_prev2
1sub 3 1
1div_prev 2
我的代码:
// Header Files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Declaring variables
int PreviousResult = 0;
string command;
string filename = "calc.txt";
int x,y,z;
int result = 0;
int numCommands = 0;
int operation = 1;
//Prompts the user to enter the text file name.
cout << "Please enter a filename: ";
cin >> filename;
//Declaring an ifstream object and opening the file
ifstream myfile(filename.c_str());
myfile.open("calc.txt");
//Will check to see if file exists. If not, it will output the following.
if(!myfile)
{
cout << "The file doesn't exist." <<endl;
return 0;
}
//While loop- read the file until the end is reached.
while(!myfile.eof())
{
myfile >> numCommands;
for(int i = 0; i < numCommands; i++)
{
myfile >> command;
//Addition
if (command=="add")
{
myfile >> x >> y;
PreviousResult = x + y;
}
//Subtraction
else if (command == "sub")
{
myfile >> x >> y;
PreviousResult = x - y;
}
//Multiplication
else if (command == "mul")
{
myfile >> x >> y;
PreviousResult=x*y;
}
//Division
else if(command=="div")
{
myfile >> x >> y;
PreviousResult = x / y;
}
else if (command == "add_prev")
{
myfile >> z;
PreviousResult += z;
}
else if (command == "sub_prev")
{
myfile >> z;
PreviousResult -= z;
}
else if (command == "mul_prev")
{
myfile >> z;
PreviousResult *= z;
}
else if (command == "div_prev")
{
myfile >> z;
PreviousResult /= z;
}
}
result = PreviousResult;
//Print the results.
cout << "The result of calculation " << operation <<" is: " << result << endl;
//The count is incremented by 1
operation ++;
}
return 0;
}
如果我正确地解释了您的程序,那么您的问题之一是由于PreviousResult没有重置。您在开始时用这行声明并初始化了PreviousResult
int PreviousResult = 0;
重置它就像重新分配其值(如)一样简单
PreviousResult = 0;
至于为什么你得到4次计算而不是3次,
while(!myfile.eof())
由于eof()只在输入流读取文件末尾后返回false,因此循环1的次数将比预期的多。直到CCD_ 1。另一种选择是进行
while(myfile >> numCommands)
而while循环将在没有更多内容要读取时终止。
问题是执行计算后没有重置PreviousResult。因此,在计算2中,您将PreviousResult设置为2,设置result=PreviousResults,然后显示结果。问题是,一旦进入计算3,PreviousResult仍然等于2。这意味着计算3是计算2除以2,而不是0除以2,从而给出错误的答案。
因此,在您设置Result=PreviousResult之后,您需要行
PreviousResult = 0;
至于第四次计算,while(!myfile.eof())可能会导致结果不一致。可能有换行符导致它尝试读取下一个空行。在while循环的左大括号后面添加myfile.ignore(),这应该可以解决问题。
相关文章:
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 我在c ++矩阵计算器程序中找不到错误
- C++计算器,不能单独除以 0
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- Arduino 基础 2 计算器无法C++工作
- 需要有关我的平均计算器代码的建议
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- C++计算器运算符
- 使用WIN32 API的击球平均计算器
- RPN计算器c++错误处理和多个运算符
- C++查找用于构建单行计算器
- 如何修复这个基本计算器
- 用于加法和减法的十六进制计算器
- 桌面计算器出现问题.C++程序设计语言
- 如何对堆栈中的所有项目求和?Postfix计算器
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 如何在我的基本计算器中循环遍历数组
- 如果 GPA 计算器的语句问题
- 我的C++计算器似乎出了什么问题?