C++求助:如何为calc3平方计算器任务构建合适循环及实现程序?
Got it, let's work through this C++ calculator problem step by step. The tricky part here is handling that special ^ notation for squaring—we can't just compute addition/subtraction as soon as we read a number; we need to hold onto it first and check if the next token is ^ before applying the operation.
Core Approach
Here's the game plan for our program:
- Use a running total (
result) to keep track of the calculation so far. - For each number we read, first check if the next character is
^—if yes, square the number immediately. - Use a variable to store the current operator (we'll default to
+for the first number since expressions start with a value). - Loop through the input file until there are no more tokens left to process.
- Use
long longfor the result to avoid integer overflow—squaring even moderately large numbers can quickly exceed the limits of a standardint.
Full Code Implementation (calc3.cpp)
#include <iostream> #include <fstream> using namespace std; int main() { ifstream inputFile("formulas.txt"); if (!inputFile.is_open()) { cerr << "Oops, couldn't open formulas.txt. Check if the file exists in the right directory!" << endl; return 1; } long long result = 0; int currentNum; char op = '+'; // Start with '+' since the first number is added to 0 while (true) { // Step 1: Read the next number. If we can't, we're done. if (!(inputFile >> currentNum)) { break; } // Step 2: Check if this number is followed by '^' char tempChar; if (inputFile >> tempChar && tempChar == '^') { currentNum *= currentNum; // Square the number // Now read the operator after the '^' (unless it's the end of the file) if (!(inputFile >> op)) { // No operator after ^—this is the last term (op == '+') ? result += currentNum : result -= currentNum; break; } } else { // Not a ^—put the character back, it's part of the next operator/end of input if (tempChar != '\0') { inputFile.unget(); } } // Step 3: Apply the current operator to the result if (op == '+') { result += currentNum; } else if (op == '-') { result -= currentNum; } // Step 4: Read the next operator for the next iteration if (!(inputFile >> op)) { break; } } cout << "Calculation result: " << result << endl; inputFile.close(); return 0; }
Breaking Down the Loop
This loop follows a read-check-process-repeat pattern tailored to handle the ^ case:
- Read the number: We start by reading a number from the file. If this fails (end of file), we exit the loop.
- Check for
^: We read the next character to see if it's^. If it is, we square the number, then read the operator that comes after the^(this operator will be used for the next term). If it's not^, we useunget()to put the character back into the input stream—this character is either the operator for the current term or the end of the file. - Update the result: We use the stored operator to add or subtract the current number from our running total.
- Read next operator: Grab the operator that will apply to the next number, then repeat the loop.
This setup ensures we never compute an operation before verifying if the number needs to be squared. The unget() function is key here—it lets us "undo" a read when we realize we grabbed the wrong token.
Testing with Your Example
For the input 10^ +7 -51^, here's how the loop processes it:
- Reads
10, sees^next, squares it to100, then reads the operator+. Adds100to the initial result (0→100). - Reads
7, no^follows. Uses the operator+to add7→ result becomes107. Reads the next operator-. - Reads
51, sees^next, squares it to2601. No operator follows, so subtracts2601from107→ final result-2494.
内容的提问来源于stack exchange,提问作者CurrentlyAnonymous

