with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure factorial_ada is
n, i : Integer;
output : Integer := 1;
begin
Put_Line("Enter the number to be taken factorial of: ");
Get(n);
-- Begin Loop
for i in 2..n
loop
output := output * i;
end loop;
Put("Factorial of ");
Put(n);
Put(" is ");
Put(output);
end factorial_ada;
Run Code Online (Sandbox Code Playgroud)
我的代码可以编译并运行,但我收到一条警告,提示“变量“i”永远不会被读取,也永远不会被赋值”“for 循环隐式声明循环变量”“声明隐藏了在第 15 行声明的“i””
我该如何解决?
如果我用-gnatl(列出带有错误消息的源代码)编译你的代码,它会给出
1. with Ada.Text_IO, Ada.Integer_Text_IO;
2. use Ada.Text_IO, Ada.Integer_Text_IO;
3.
4. procedure factorial_ada is
5.
6. n, i : Integer;
|
>>> warning: variable "i" is never read and never assigned
7. output : Integer := 1;
8.
9. begin
10. Put_Line("Enter the number to be taken factorial of: ");
11. Get(n);
12.
13. -- Begin Loop
14. for i in 2..n
|
>>> warning: for loop implicitly declares loop variable
>>> warning: declaration hides "i" declared at line 6
15. loop
16. output := output * i;
17. end loop;
18.
19. Put("Factorial of ");
20. Put(n);
21. Put(" is ");
22. Put(output);
23.
24. end factorial_ada;
Run Code Online (Sandbox Code Playgroud)
第 14 行的警告提醒您(ARM 5.5(11))
不应为循环参数提供 object_declaration,因为循环参数是由 loop_parameter_specification 自动声明的。循环参数的范围从 loop_parameter_specification 延伸到 loop_statement 的末尾,可见性规则是这样的,循环参数仅在循环的 sequence_of_statements 内可见。
第 6 行的警告告诉您这i(用 ARM 来说是“对象声明”)与第i14 行无关。
这类似于 C++ 规则:编写
#include <stdio.h>
int main() {
int i;
int output = 1;
int n = 12;
for (int i = 2; i <= n; i++) {
output *= i;
}
printf("factorial %d is %d\n", i, output);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是
$ g++ hk.cc -Wall
hk.cc: In function 'int main()':
hk.cc:9:9: warning: 'i' is used uninitialized in this function [-Wuninitialized]
9 | printf("factorial %d is %d\n", i, output);
| ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)