簡體   English   中英

為什么減法時得到0而不是負數?

[英]Why do i get 0 instead of negative number when subtracting?

我試圖解決“codewars”kata。 起初看起來很容易。 當我編寫程序時,它只有在返回值為正時才能正常工作。 所以,當結果是正數時,沒關系,但是,當嘗試減去時,我總是得到 0 而不是負數。 我認為問題可能出在int的類型上。 所以我嘗試將其更改為signed int 但這沒有幫助。

因此,任務聽起來像這樣:您必須對給定的字符串進行加減運算。 返回值也必須是字符串。

例子:

"1加2加3加4" --> "10"

"1加2加3減4" --> "2"

這是我的代碼:

#include <string>

std::string calculate(std::string str)
{
    std::string temp; signed int result = 0;

    for (auto& x : str)
    {
        if (std::isdigit(x) && result == 0 )
                               result = std::stoi(std::string(1,x));

        if (std::isdigit(x) && result !=0 )
        {
            if (temp == "plus")   // if it's operation PLUS than add
            {
                result += std::stoi(std::string(1,x)); // c++always get 0 instead of signed int
            }
            else          // if operation MINUS than subtract
            {
                result -= std::stoi(std::string(1,x));   // here always get result as 0
            }
            temp = "";
        }
        if (std::isalpha(x)) temp += x;
    }
    return std::to_string(result-1);
}

您的循環不應該檢查result == 0 / result != 0以了解result是否有值。 想想如果在迭代的中途運行結果實際上是0會發生什么,即"1plus1minus..."

如果您使用調試器單步執行您的代碼,您會看到在第 1 次迭代x'1' ,因此if (std::isdigit(x) && result == 0 )為真,則result設置為1 ,但是下面的if (std::isdigit(x) && result !=0 )現在為真。 但是temp尚未設置為任何值,因此if (temp == "plus")為假,並且循環落入從result中減去的代碼中,從而使其成為0 ,而它根本不應該改變result

嘗試更多類似的東西:

#include <string>

std::string calculate(const std::string &str)
{
    std::string temp;
    int result = 0;

    if (!str.empty() && std::isdigit(str[0]))
    {
        result = str[0] - '0';

        for (size_t i = 1; i < str.size(); ++i)
        {
            char x = str[i];

            if (std::isdigit(x))
            {
                int num = (x - '0');
 
                if (temp == "plus")
                {
                    result += num;
                }
                else if (temp == "minus")
                {
                    result -= num;
                }
                temp = "";
            }
            else if (std::isalpha(x))
                temp += x;
        }
    }

    return std::to_string(result);
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM