I would like to create a program for darts, I walked up to a problem.
s1 := Form1.Edit1.Text;
s2 := Form1.Edit2.Text;
s3 := Form1.Edit3.Text;
x1 := StrToFloat(s1);
x2 := StrToFloat(s2);
x3 := StrToFloat(s3);
score1 := (score1 - x1 - x2 - x3);
ss1 := FloatToStr(score1);
Form1.Edit7.Text := ss1;
score1 should be 501 at start and count down, so score 1 is at the start 501 you fill in 3 numbers and it should be 501-1-1-1 (for example) and then the next time it should be 498-1-1-1
How can i do this?
I dont have any problems or errors, i just dont know how to do this.
I use lazarus to write the program.
I hope i explained this well enough.
Ok, I will outline how you might do this, but leave the coding up to you.
First you need to read up about programming loops - see for example
https://www.tutorialspoint.com/pascal/pascal_loops.htm
Typically, with a task like this, you start by setting some initial condition(s) before the loop first executes. In your case, I think it would be better to back-track slightly from there and choose a better name for your score variable. Personally, I would base the name on Target, and actually have two variables, Target, that you initialize before the loop (to 501) and RunningTarget that you initialize to equal Target before the loop, and update each time around the loop (as in your score1 := (score1 - x1 - x2 - x3))
The type of loop - see the article - is up to you. It will need a terminating condition which decodes whether to continue looping or to stop. Again that's for you to decide and code.
Finally, you need to think about why you feel the need to call FloatToStr and what you are trying to achieve by this - after all the RunningTotal's value will be a whole number, won't it?
Have fun!
Btw, the reason I suggested thinking about a different variable name is that you should always have in the back of your mind whether it will mean the same thing to you in 6 months' time - or to another reader. To me, 'score' sounds like the value should be increasing, whereas your code will do the exact opposite.
Related
I'm doing some homework and there's this problem where I have to make a program that tells me how many prime numbers there are between two numbers given by the user. For some reason, when I test the program with F8 I can see the program bounces back and forth between "for" and "if", for no apparent reason. And yes, I HAVE to use this language.
I have tried restanting the IDE, hoping it'ts just some bug (like it often happens on Android Studio). I don't know what else to try, this is the first time I use Lazarus and PASCAL.
program PrimoEntre;
var
a, b, i, q: Integer;
begin
write('Ingrese el primer valor: ');
readln(a);
write('Ingrese el segundo valor: ');
readln(b);
for i:=a to b do //It starts bouncing back and forth from here...
begin
q:=2;
if((b>=2)AND(b<=10)) then //...to here.
begin
while((q>=2) and (q<=b)) do
begin
if(a<>b) then
begin
if((a MOD b)=0) then
begin;
//i ES NO PRIMO
if(q=b) then
begin
writeln('No existen numeros primos entre ', a, ' y ', b, '.');
end;
q:=(q+1);
end;
end
else
begin
if(q=b) then
begin
//i ES PRIMO
writeln(i, ' es primo.');;
q:=1
end;
end;
end;
end
else
begin
while((q>=2) and (b<=10)) do
begin
if(a<>b) then
begin
if((a MOD b)=0) then
begin
//i ES NO PRIMO
if(q=b) then
begin
writeln('No existen numeros primos entre ', a, ' y ', b, '.');
end;
q:=(q+1);
end;
end
else
begin
if(q=b) then
begin
//i ES PRIMO
writeln(i, ' es primo.');
q:=1
end
end;
end;
end;
end;
readln();
end.
I expect the output to be one of the following:
-The console writing every time it finds a prime number between a and b.
-The console saying there isn't any prime number between a and b.
Instead, there's no result. The program just gets stuck and I have to terminate it manually.
You say you are trying to find prime numbers in the range a...b. The problem is that
you are doing this in a quite unnecessarily complicated way and the main reason
your program is jumping all over the place is that you are making it do so because
you are making the value of your q variable jump all over the place.
What I think you should do it to slow down and think what you are trying to do:
You want to iterate the integers in the range a to b. Your for loop does
this fine, with the value of i being what you are testing for primality. I'm going
to refer to this as your outer for loop.
Where you go wrong is to needlessly execute a while loop to test for primality.
Once you have established the i value you are testing, what you want to do is to
test whether there is any factor of i which is other than 1 or i. To do that, you
can use a simple, inner for loop which iterates a value j (so-called to avoid
confusion with your q) to determine whether i is divisible by j with zero remainder using
a mod test:
if it is, there is no point in continuing with the inner, j loop.
The next thing to consider is what should be the upper limit of the
loop for j := ... to ... should be. It is pointless to consider values
of j which are higher than the square root of i for the obvious reason
that if i has an intger factor greater than that, it must also have one
which is lower.
If the j loop completes without finding a factor, i is prime.
Try coding the inner, j loop, and you will see how the result is vastly
simpler (and more predictable) than your existing code, and with very few
opportunities for coding error, and vastly simpler to debug because execution
just "falls" through it for each value of i.
Btw, I completely agree with #TomBrunberg about structured coding as a general proposition, but I think that the two nested for loops you need here don't really need separating into different procedures/functions, though you might try
that once you've got the code working properly.
The causes of your error are a mix between the fact that the problem is highly depending on your input and that you are not treating some cases in else causes.
As an example, I ran your program with a=20 and b=30. The program ran into the for loop, which is correct. However, the (b>2) and (b<=10) condition is false, which made the compiler go to the else branch. However, the first thing it met there was while (q>=2) and (b<=10) which is, from the start, false. There it bounces back as you said in your question.
With a=2 and b=9, your program has a total different behavior.
How to fix it? I guess you first have to clarify what you want. Then, I think, the fix will be obvious.
Your program lacks structure because the whole program is crammed in the main procedure.
As a consequence of the previous, it has too many 'indentation levels' or 'logical chains' to be readable and manageable. With indentation levels or logical chains I mean e.g. your:
'for<condition> - if<condition> - while<condition> - if<condition> - if<condition> - if<condition> - writeln().
Because of the long chains of conditions, it is hard to evaluate what a change will effect, and you might find yourself deeper and deeper in trouble, when you try to fix something.
I suggest you ditch what you have now, and divide your program into procedures / functions according to main operations: for example GetUserEntry(var a, b: integer), function IsPrime(x: integer): boolean, procedure ShowResult() and the main program (GetUserEntry, for a to b if IsPrime then add to outstring, ShowResult(outstring)).
Finally, format your code to be readable using proper indentation.
I can't debug one of my programs for a year now. When I press the green Run button, the following error message appears:
The full text is:
The GDB command:
"-exec-run"
returned the error:
",msg="Error creating process C:/Users/leven/OneDrive/J\341t\351kpogramok/People/people.exe, (error 193).""
I've read many forums about this error, but my case looks a bit different...
As you can see, the file's path doesn't include any characters that could occur this problem (no spaces, no special letters). I've tried running outside OneDrive, same error.
I've spent a lot of time looking for something in my program that occurs this error and found that if I delete some parts of it (eg. a few procedures or functions, which contains a lot of code though), the program is debuggable again! So the trouble is with some parts of the program, but I still don't know the exact problem.
As I can remember, I've always debugged this program in a 64bit OP.
The one thing that could be problematic is that I probably started writing the program using Windows 7 or 8, and now I want to run it using Windows 10, but I still don't understand, why deleting some parts of the program is a solution...
Thanks in advance for your help!
UPDATE:
I've found, that the line
p[x,y,2,1]:=r;
cannot be debugged by the compiler.
Description:
p: array [1..15000, 1..10000, 1..7, 1..4] of integer;
p[] is a game field. The first two parameters are coordinates, the third and the fourth are not important.
x, y and r are integers.
So, the command seen above writes a number into the game field (p[]) array using the x, y coordinates.
I think we established through a series of queries in comments that the necessary and sufficient condition to provoke the debugger problem you've been getting is to include in your app the declaration of the array p that you've added to your q, that is:
var
p: array [1..15000, 1..10000, 1..7, 1..4] of integer;
For you, it seems that just including this declaration in your code is sufficient to make the debugger throw the error you quote.
For me the debugger starts fine but I get a SIGSEGV error on the assignment to p[] in the following code:
var
p: array [1..15000, 1..10000, 1..7, 1..4] of integer;
x,
y,
r : integer;
begin
x := 100;
y := 100;
r := 666;
p[x, y, 1, 1] := r;
writeln('Press any key ...');
readln;
end.
So, I would try smaller values for the first two bounds of the p array. If that works and you still need the original bounds, I would suggest looking for an FPC library which implements "sparse arrays" and declare p as one of those.
Good luck!
I realize similar questions have been asked here and here -- but they weren't very clear and I just wanted to see if anything has changed since these were asked over a year ago.
Scenario: I have 3 values displayed to the user: A and B are returned from the API, and X is supposed to be the result of subtracting A - B. The values of A and B are floats on the backend, but are parsed to an Integer on the frontend so the user never sees the decimal values, thus Protractor doesn't know their real value (whether they were rounded up or down). So, my value of X will frequently be +/- 1 from the expected value.
Use Case: expect(someVar).toEqual(x || y);
Question: Has Jasmine implemented anything like an OR statement to execute in one expect? Otherwise I need to create a custom matcher.
Would the toBeWithinRange jasmine matcher, coming from the jasmine-matchers help:
expect(someVar).toBeWithinRange(expectedValue - 1, expectedValue + 1);
There is also a related thread with several more options:
Expect item in array
As the title says I'm curious about the difference between "call-by-reference" and "call-by-value-return". I've read about it in some literature, and tried to find additional information on the internet, but I've only found comparison of "call-by-value" and "call-by-reference".
I do understand the difference at memory level, but not at the "conceptual" level, between the two.
The called subroutine will have it's own copy of the actual parameter value to work with, but will, when it ends executing, copy the new local value (bound to the formal parameter) back to the actual parameter of the caller.
When is call-by-value-return actually to prefer above "call-by-reference"? Any example scenario? All I can see is that it takes extra memory and execution time due to the copying of values in the memory-cells.
As a side question, is "call-by-value-return" implemented in 'modern' languages?
Call-by-value-return, from Wikipedia:
This variant has gained attention in multiprocessing contexts and Remote procedure call: if a parameter to a function call is a reference that might be accessible by another thread of execution, its contents may be copied to a new reference that is not; when the function call returns, the updated contents of this new reference are copied back to the original reference ("restored").
So, in more practical terms, it's entirely possible that a variable is in some undesired state in the middle of the execution of a function. With parallel processing this is a problem, since you can attempt to access the variable while it has this value. Copying it to a temporary value avoids this problem.
As an example:
policeCount = 0
everyTimeSomeoneApproachesOrLeaves()
calculatePoliceCount(policeCount)
calculatePoliceCount(count)
count = 0
for each police official
count++
goAboutMyDay()
if policeCount == 0
doSomethingIllegal()
else
doSomethingElse()
Assume everyTimeSomeoneApproachesOrLeaves and goAboutMyDay are executed in parallel.
So if you pass by reference, you could end up getting policeCount right after it was set to 0 in calculatePoliceCount, even if there are police officials around, then you'd end up doing something illegal and probably going to jail, or at least coughing up some money for a bribe. If you pass by value return, this won't happen.
Supported languages?
In my search, I found that Ada and Fortran support this. I don't know of others.
Suppose you have a call by reference function (in C++):
void foobar(int &x, int &y) {
while (y-->0) {
x++;
}
}
and you call it thusly:
int z = 5;
foobar(z, z);
It will never terminate, because x and y are the same reference, each time you decrement y, that is subsequently undone by the increment of x (since they are both really z under the hood).
By contrast using call-by-value-return (in rusty Fortran):
subroutine foobar(x,y):
integer, intent(inout) :: x,y
do while y > 0:
y = y - 1
x = x + 1
end do
end subroutine foobar
If you call this routine with the same variable:
integer, z = 5
call foobar(z,z)
it will still terminate, and at the end z will be changed have a value of either 10 or 0, depending on which result is applied first (I don't remember if a particular order is required and I can't find any quick answers to the question online).
Kindly go to the following link , the program in there can give u an practical idea regarding these two .
Difference between call-by-reference and call-by-value
I wanted to know, how to evaluate multiple statements in a function in Mathematica.
E.g.
f[x_]:=x=x+5 and then return x^2
I know this much can be modified as (x+5)^2 but originally I wanted to read data from the file in the function and print the result after doing some data manipulation.
If you want to group several commands and output the last use the semicolon (;) between them, like
f[y_]:=(x=y+5;x^2)
Just don't use a ; for the last statement.
If your set of commands grows bigger you might want to use scoping structures like Module or Block.
You are looking for CompoundExpression (short form ;):
f[x_]:= (thing = x+5 ; thing^2)
The parentheses are necessary due to the very low precedence of ;.
As Szabolcs called me on, you cannot write:
f[x_]:= (x = x+5 ; x^2)
See this answer for an explanation and alternatives.
Leonid, who you should listen to, says that thing should be localized. I didn't do this above because I wanted to emphasize CompoundExpression as a specific fit for your "and then" construct. As it is written, this will affect the global value of thing which may or may not be what you actually want to do. If it is not, see both the answer linked above, and also:
Mathematica Module versus With or Block - Guideline, rule of thumb for usage?
Several people have mentioned already that you can use CompoundExpression:
f[x_] := (y=x+5; y^2)
However, if you use the same variable x in the expression as in the argument,
f[x_] := (x=x+5; x^2)
then you'll get errors when evaluating the function with a number. This is because := essentially defines a replacement of the pattern variables from the lhs, i.e. f[1] evaluates to the (incorrect) (1 = 1+5; 1^2).
So, as Sjoerd said, use Module (or Block sometimes, but this one has caveats!) to localize a function-variable:
f[x_] := Module[{y}, y=x+5; y^2]
Finally, if you need a function that modified its arguments, then you can set the attribute HoldAll:
Clear[addFive]
SetAttributes[addFive, HoldAll]
addFive[x_] := (x=x+5)
Then use it as
a = 3;
addFive[a]
a