當我試圖計算偶數的總和時,如果起始數字是負數,結果是不正確的?爲什麼在C++中顯示不正確的總和?
下面是代碼:
#include <iostream>
using namespace std;
int main() {
signed int startingNumber, upperLimit;
signed int result = 0;
cout << "please enter the starting number: "; cin >> startingNumber;
cout << "please enter the upper limit: "; cin >> upperLimit;
while (true) {
if (startingNumber % 2 != 0) result += startingNumber;
if (upperLimit == startingNumber) break;
startingNumber++;
}
cout << "The result is: " << result << endl;
}
但是當我運行該腳本下面是結果:
please enter the starting number: -2
please enter the upper limit: 4
The result is: 3
我想結果應該是4不是3,作爲計算 - 2 0 + 2 + 4 = 4
問候,,,