运行时C++数学无法正常工作 我正在尝试做这个C++程序,它把两个数之间的自然数相加。守则: #include <iostream> using namespace std; int main() { int number, limit, sum = 0; char ch; do { cout << "Enter the initial number: "; cin >> number; cout << "Enter the last number: "; cin >> limit; while (number <= limit) { sum += number; ++number; } cout << endl; cout << "The sum of all the numbers between the two number you entered is ==> " << sum; cout << endl << endl; cout << "Do you want to calculate again? y-YEs n-No: "; cin >> ch; cout << endl; if (ch == 'n' || ch == 'N') { cout << "Thank you for using our program. Peace :)\n\n"; } } while (ch == 'y' || ch == 'Y'); return 0; }

运行时C++数学无法正常工作 我正在尝试做这个C++程序,它把两个数之间的自然数相加。守则: #include <iostream> using namespace std; int main() { int number, limit, sum = 0; char ch; do { cout << "Enter the initial number: "; cin >> number; cout << "Enter the last number: "; cin >> limit; while (number <= limit) { sum += number; ++number; } cout << endl; cout << "The sum of all the numbers between the two number you entered is ==> " << sum; cout << endl << endl; cout << "Do you want to calculate again? y-YEs n-No: "; cin >> ch; cout << endl; if (ch == 'n' || ch == 'N') { cout << "Thank you for using our program. Peace :)\n\n"; } } while (ch == 'y' || ch == 'Y'); return 0; },c++,visual-studio,C++,Visual Studio,尝试从1到10之间的数字,它输出55,这是正确的。但当我尝试从1到11的数字时,它输出121,这是错误的。我使用的是VisualStudio2019,我试着用跟踪来调试它,当我观察变量时没有错误的输出。问题只在程序执行时出现 有人能帮我吗,我是初学者。您的变量声明和初始化: int number, limit, sum = 0; 在进入循环之前,所有这些都会发生一次。所以你实际上是在多次运行中保持一个运行总数 要解决此问题,只需确保在每个循环开始时将sum重置为0: do { sum

尝试从1到10之间的数字,它输出55,这是正确的。但当我尝试从1到11的数字时,它输出121,这是错误的。我使用的是VisualStudio2019,我试着用跟踪来调试它,当我观察变量时没有错误的输出。问题只在程序执行时出现


有人能帮我吗,我是初学者。

您的变量声明和初始化:

int number, limit, sum = 0;
在进入循环之前,所有这些都会发生一次。所以你实际上是在多次运行中保持一个运行总数

要解决此问题,只需确保在每个循环开始时将sum重置为0:

do {
    sum = 0;

    cout << "Enter the initial number: ";
    // ...

这不是编译,发布你真正的代码。从第一行到最后一行发布整个代码。我猜你实际上在使用do{loop,你忘了重置sum。因此,第二次循环时,它的值来自第一次循环。你忘了将每个循环的sum重置为0。一个好习惯是尽可能接近其用途来声明和初始化变量。为什么不在循环内声明sum呢?@cigien那也行。就我个人而言,我更喜欢在e而不是在每个循环中重新声明它们。但是我也知道ppl喜欢他们的变量的范围是为了防止错误。是的,这是我声明变量尽可能接近它们的用法的主要原因。而且,这样对我来说更易读。