任务D.计算3:正方形。如何为我的作业构建一个合适的循环?C+ [英] Task D. Calc3:Squares. how to construct a proper loop for my assignment? C++

查看:58
本文介绍了任务D.计算3:正方形。如何为我的作业构建一个合适的循环?C+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关编码作业的帮助。

编写一个更好的计算器程序calc3.cpp(仅使用iostream),它可以理解平方数。我们将使用简化的记数法X^表示X^2。例如,10^+7-51^应该表示10^2+7−51^2。 示例: 读取输入文件时公式.txt

5^;
1000 + 6^ - 5^ + 1;
15^+15^;

程序应报告:

$ ./calc3 < formulas.txt
25
1012
50625

提示: 要考虑^,不要在阅读新数字后立即添加或减去它们。相反,记住数字,读下一个运算符,如果是^,则将记住的数字平方,然后加或减。

我目前拥有的内容:

#include <iostream>
using namespace std;
int main() 
{
int numbers,firstnum;
char operators ; // for storing -+;^ from the txt file
int sum = 0;
cin >> firstnum; // stores the 1st integer of the expression found in the txt file. 
while(cin >> operators >> numbers)
 { // while loop for storing characters and int 

    if(numbers>=0 and operators =='+')//adding
    {
        firstnum+=numbers;
    }
    else if (numbers>=0 and operators == '-')//subtracting
    {
        firstnum-=numbers;
    }
    if (operators==';') // semicolon:ends the loop for each expression
    {
    cout<<firstnum<<'
';
    firstnum=0+numbers;
    }

 }  
sum=firstnum; // for the last expression not picked up by the while-loop
cout<<sum;

}

我需要帮助构造While循环,以便"^"不会中断循环。

推荐答案

在解析术语中,^优先于+-。也就是说,在计算加法和减法之前,必须首先应用^。在知道数字后的下一个令牌是否为^之前,不应进行加/减操作;因为如果是,则需要首先执行平方运算。

例如,考虑以下输入文件:

1 + 3^;
现在,您的程序将读取1并将其存储在firstnum中。然后程序读取+(将其存储在operators中)和3(将其存储在numbers中)。然后您的程序达到numbers>=0 and operators =='+'情况,因此firstnum+=numbers;被求值,firstnum变为4。但是,这是一个错误,因为下一个令牌是^,所以应该首先将3平方。

考虑另一个例子:

4^ + 1;
您的程序当前将4读取为firstnum^读取为operators,然后尝试将+解析为整数。此操作失败,导致在cin上设置失败位,并且cin >> operators >> numbers计算为false

当表达式以-

开头时,您可能需要处理一种特殊情况
-9^;
-10^ + 11^;

此外,您可能需要澄清应如何处理以下情况:

1^ + -2^;
1^ - -2^;
2^^^;

这篇关于任务D.计算3:正方形。如何为我的作业构建一个合适的循环?C+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆