仅返回 x=a 或变量'start'的第一个值

Only returns the first value of x=a or 'start' variable

本文关键字:start 第一个 变量 返回      更新时间:2023-10-16
#include <iostream>
using namespace std;
int sumTo(int a, int b);

int main()
{
int start;
int end;
cout << "Enter one number " << endl;
cin >> start;
cout << "The second number  " << endl;
cin >> end;
int total = sumTo(start, end);

cout << "The sum of the integers btween these 2 numbers is " <<total<<endl ;
return 0;
}
int sumTo(int a, int b)
{
    int sum = 0;
    for (int x = a; x <= b; x++)
    {
        sum += x;
        cout << sum << endl;
        return sum;
    }
}

嗨,对于这个,它需要找到两个输入数字之间的所有数字的和。现在它只返回第一个输入数字不知道为什么?

代码的问题是return sum;被放置在for循环中。这将导致for循环只运行一次,因为函数已经返回了sum的值,即a

int sumTo(int a, int b)
{
    int sum = 0;
    for (int x = a; x <= b; x++)
    {
        sum += x;
        cout << sum << endl;
        return sum; // Here is your problem.
    }
}

你的函数应该是

int sumTo(int a, int b)
{
    int sum = 0;
    for (int x = a; x <= b; x++)
    {
        sum += x;
        cout << sum << endl;
    }
        return sum; // This line should be placed here instead.
}