You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 long for the result to avoid integer overflow—squaring even moderately large numbers can quickly exceed the limits of a standard int.

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:

  1. Read the number: We start by reading a number from the file. If this fails (end of file), we exit the loop.
  2. 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 use unget() 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.
  3. Update the result: We use the stored operator to add or subtract the current number from our running total.
  4. 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:

  1. Reads 10, sees ^ next, squares it to 100, then reads the operator +. Adds 100 to the initial result (0 → 100).
  2. Reads 7, no ^ follows. Uses the operator + to add 7 → result becomes 107. Reads the next operator -.
  3. Reads 51, sees ^ next, squares it to 2601. No operator follows, so subtracts 2601 from 107 → final result -2494.

内容的提问来源于stack exchange,提问作者CurrentlyAnonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:13:18