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; 我的代码可以编译并运行,但是我得到了一个警告,它说“变量"i”永远不会被读取和赋值“"for loop隐式声明循环变量”“声明隐藏了在第15行声明的"i”“
我该如何解决这个问题?
发布于 2020-03-03 04:28:33
如果我用-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;第14行的警告提醒您(ARM 5.5(11))
不应为循环参数提供object_declaration,因为循环参数是由loop_parameter_specification自动声明的。循环参数的作用域从loop_parameter_specification延伸到loop_statement的末尾,可见性规则使得循环参数仅在循环的sequence_of_statements中可见。
第6行的警告告诉您,此i (ARM语言中的“对象声明”)与第14行的i无关。
这类似于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;
}结果:
$ 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);
| ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~https://stackoverflow.com/questions/60495097
复制相似问题