在这个程序中,我试图使用重复添加来实现square函数。 我得到的输出只是x(输入)值的两倍。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int square (int x) {
for (int i = 0; i <= x; ++i) {
x += x; // adding the value of x to x each time
return x;
}
}
int main()
{
int x;
cout << "Enter a value for x" << endl;
cin >> x;
cout << square (x);
}
答案 0 :(得分:0)
你必须将代码改为以下代码:
for (int i = 0; i <= x; ++i) {
x += x; // adding the value of x to x each time
}
return x;
您的代码无法正常工作的原因是您在返回元素int for
循环。你也必须改变累加器。
int result = 0;
for (int i = 0; i < x; ++i) {
result += x; // adding the value of x to the accumulator.
}
return result;
答案 1 :(得分:0)
使用此代码处理负输入
int square (int x)
{
unsigned int result = 0;
unsigned int absolute_x = std::abs(x);
for (unsigned int i = 0; i < absolute_x; ++i)
{
result += absolute_x;
}
return result;
}
答案 2 :(得分:0)
int square (int x) {
for (int i = 0; i <= x; ++i) {
x += x; // adding the value of x to x each time
return x;
}
}
你的return x;
在你的循环中,所以在它第一次返回后增加x的值时,你也不能说i <= x
,因为你将改变值x。因此,如果你想让你的代码工作,你需要在函数的末尾放置return x;
并创建另一个int变量来记住x的值,否则你将以无限循环结束,你的程序会崩溃。
int square (int x) {
int j = x;
for (int i = 0; i <= j; ++i) {
x += x; // adding the value of x to x each time
}
return x;
}
这样它会添加,直到你有x = x ^ 2然后它将退出循环并返回值。
您也可以使用数学库中的sqrt(x)获得相同的结果。但请注意,return
始终以与break;
相同的方式运行,因此当它到达该点时,它将停止执行循环(和函数/程序)。例如,您可以编写代码,如:
while(1){
++i;
if(i>j) return x;
x+=x;
}