【问题标题】:Variables not declared in scope error/too few arguments to function未在作用域错误中声明的变量/函数的参数太少
【发布时间】:2018-07-02 19:01:59
【问题描述】:

我正在编写一个简单的代码,以根据用户输入获取一个数字和一个幂,并使用函数将数字与该幂平方。但是,在尝试编译代码时,我遇到了多个错误。这是代码:

#include <iostream>
using namespace std;

double power(double& n1, sq)
{
    for (int i = 0; i < sq; i++) {
        n1* n1;
    }
    return n1;
}

int main()
{
    double power(double&);
    double num1, square;
    cout << "Enter a number IMMEDIATLY: ";
    cin >> num1;
    cout << "\nEnter a power: ";
    cin >> square;
    power();
    cout << num1 << endl;
    return 0;
}

以下是我收到的错误:

||=== Build: Debug in practice (compiler: GNU GCC Compiler) ===|
|5|error: 'sq' has not been declared|
In function 'double power(double&, int)':|
|6|error: 'sq' was not declared in this scope|
|7|warning: statement has no effect [-Wunused-value]|
In function 'int main()':|
|22|error: too few arguments to function 'double power(double&)'|
|15|note: declared here|
|17|warning: unused variable 'ans' [-Wunused-variable]|
||=== Build failed: 3 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|

任何有关如何修复这些错误的帮助或说明将不胜感激,因为我已经被难住了一段时间。谢谢!

编辑:所以我已将 square 解析为 int 并将变量初始化为 power() (正如你们所说),但现在代码产生了不正确的答案作为输出(任何大于平方数字都会产生不正确的输出)。

#include <iostream>

using namespace std;

double power(double& n1, int& sq) {
for (int i=2; i<=sq; i++) {
        n1*=n1;
}
return n1;

}

int main()
{
double power(double& n1, int& sq);
double num1;
int square;
cout << "Enter a number IMMEDIATLY: ";
cin >> num1;
cout << "\nEnter a power: ";
cin >> square;
 power(num1, square);
cout << num1 << endl;
return 0;
}

【问题讨论】:

  • 你需要在这里指定sq的类型(如果你真的想给你的函数传递一个sq参数):double power(double&amp; n1, sq)
  • double power(double&amp;); 与之前的签名不符。
  • power(); 您忘记将 1 或 2 个参数传递给 power()。由于函数签名的不同,我说 1 或 2。你必须先解决这个问题。
  • sq 可能应该是一个整数。
  • n1* n1; 什么都不做。你的意思可能是n1 *= n1;

标签: c++ function codeblocks


【解决方案1】:

要回答您的第二个问题,只需通过示例跟踪代码即可:

假设输入是

n1 = 3
sq = 3

我们知道3^3 = 27,所以让我们看看我们是否能得到答案。

首先,操作n1 *= n1 将n1 与自身相乘。仅用于平方,这很好:3*3 = 9。但是你再循环一遍,n1 现在是 9,所以代码将计算 9*9 = 81

看看你能不能从这里弄明白。提示:你需要另一个变量来存储。

此外,您的 return 语句位于 power() 函数的括号之外。虽然它自己工作,因为您传递了&amp;n1 作为参考。要么完全删除 return 语句,要么在 main 中创建一个从 power() 接收值的新变量。如果您执行后者,请删除&amp; 符号并将return 语句放在电源括号内。要更好地理解按引用传递与按值传递,请参阅this link。祝你好运!

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多