我想創建一個程序,該程序讀取包含兩個數字和一個運算符的字符串並打印出結果。它在算術運算符上不斷出現錯誤。例如,我將如何將兩個字符串添加到一起?如何對C++中的字符串應用算術運算?
int main()
{
string number1;
string number2;
string operation;
string answer;
cout << "Enter numbers with respective operations";
cout << "number 1";
cin >> number1;
cout << "number2";
cin >> number2;
cout << "operation";
cin >> operation;
if (operation == "+")
{
answer = number1 + number2;
cout << "the sum is " << answer << endl;
}
else if (operation == "-")
{
answer = number1 - number2;
cout << "the difference is " << answer << endl;
}
else if (operation == "*")
{
answer = number1 * number2;
cout << "the product is " << answer << endl;
}
else if (operation == "/")
{
answer = number1/number2;
cout << "the answer is " << answer << endl;
}
else
{
cout << "invalid input" << endl;
}
getchar();
return 0;
}
你在期待'string'除以'string'得到的結果是什麼? – Xirema
有什麼錯誤? – user463035818
根據你的代碼,沒有理由將數字作爲字符串,他們爲什麼? ,因爲它們是你需要將它們轉換爲數字的字符串,如果你想用它們來計算的話。 – xyious