我只需要仔细检查我的解决方案,但在网上找不到任何解决方案。
如果你能帮助我,我会很高兴,因为我已经为自己设定了一个在假期学习 C++ 的目标。
特别是我在功能练习方面需要帮助,这是我目前所拥有的:
//(not using multiplication)
int square(int a)
{
int result = 0;
int count = 0;
while (count < a)
{
result += result;
++count;
return result;
}
}
int main()
{
int x = 0;
x = square(5);
cout << x;
}
但我的输出是 0。
答案 0 :(得分:0)
result
是 0
,因此无论添加多少次,都将导致 0
。如果您尝试平方 a
,则应将其添加到 result
。此外,return
语句应该在循环外,而不是在循环内:
int square(int a)
{
int result = 0;
int count = 0;
while (count < a)
{
result += a; // Here!
++count;
}
return result;
}