问题
I'm new to Pascal and I am trying to write a simple program, but an having trouble passing values between functions. This is a small piece of what I have:
program numberConverter;
const
maxValue = 4999;
minValue = 1;
var num: integer;
function convertNumeral(number: integer):string;
var j: integer;
begin
if ((number < minValue) OR (number > maxValue)) then
begin
writeln(number);
writeln('The number you enter must be between 1 and 4999. Please try again:');
read(j);
convertNumeral := convertNumeral(j);
end
else
if (number >= 1000) then
convertNumeral := 'M' + convertNumeral(number -1000)
{more code here, left it out for space}
end;
begin
writeln;
writeln('Enter an integer between 1 and 4999 to be converted:');
read(num);
writeln;
writeln(num);
writeln(convertNumeral(num));
end.
My problem is that the value from the writeln(converNumeral(num)), mainly 'num', does not get passed to the convertNumeral function and was wondering if Pascal even does this. I figure its because I haven't declared number to be a variable, but when I do I get a compile error that it can't complete the second if statement. Thanks for your time.
回答1:
Yes, values definitely get passed to functions. I promise that num
really does get passed to convertNumeral
. Within that function, number
acquires whatever value resides in num
. Perhaps there's a problem with how you're observing the behavior of your program.
Changes you make to number
, if any, will not be reflected in num
. The parameter was passed by value, so number
stores a copy of the value stored in num
; they're two distinct variables. You can use var
to pass parameters by reference, if that's what you want.
Each recursive call to convertNumeral
gets a new instance of number
, so changes made to number
, if any, will not appear once the function returns to the caller. Each call gets its own versions of number
and j
.
来源:https://stackoverflow.com/questions/10097393/does-pascal-support-passing-parameters-to-functions