仅返回 x=a 或变量'start'的第一个值
Only returns the first value of x=a or 'start' variable
#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.
}
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 为什么我的代码在第一个 if 语句处中断?
- 是否可以从另一个类对象调用一个类函数而不继承第一个类
- 无法使我的第一个Windows OpenGL窗口抬起并运行
- 将参数初始化为构造函数,而不是第一个
- 仅返回 x=a 或变量'start'的第一个值