繁体   English   中英

C++:如何编写一个循环,该循环接受两个用户提示的整数并打印包含的总和?

[英]C++ : How do I write a loop that takes two user prompted integers and prints the sum inclusive?

我误读了 C++ Primer, 5th Edition 中的一个练习,认为它说“编写一个程序提示用户输入两个整数。打印两个数字之间范围内所有数字的总和”。 这不是它所说的,但我无法做到这一点。 我的最后一次尝试如下。 我正在学习循环,但我不确定我做错了什么。

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main() {

    int sum = 0, val = 0, v2 = 0;
    cout << "Enter two numbers separated by a space" << endl;
    cout << "Make sure the first number is smaller than the second" << endl;
    cin >> val >> v2;;
    cout << endl;

    while (val <= v2) {
        val += sum;
        ++sum;
    }
    cout << sum << endl;
    return 0;

}

如果需要循环

int temp = val; // keeping val unchanged
while (temp <= v2) {
    sum += temp;
    temp++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM