Error incompatible types got extended expected smallint

[Turbo Pascal] ➣ Задача: Error: Incompatible types: got "Extended" expected "SmallInt ➣ Исходный код программы ➣ Помощь

Формулировка задачи:

Задание.

Написать программу решения задачи, используя функции: в основной функции вычислить с помощью генератора случайных чисел 10 элементов массива, во вспомогательной — вычислить скалярную величину.
Проблема в том что я не смог сделать правильно задание на Паскале.

Программа нормально работает

На паскале:

как это исправить ?

Код к задаче: «Error: Incompatible types: got «Extended» expected «SmallInt»»

textual

const
  n = 10;
type
  mas=array[1..n] of integer;
 
function F(X:mas):real;
  function L(X:mas):real;
  var
    Pr : real;
    i : integer;
  begin
    Pr:=1;
    for i:=1 to n do
      Pr:=(1+abs(X[i]));
    L:=Pr
  end;
 
var
  i:integer;
  sum : real;
begin
  sum:=0;
  for i:=1 to n do
    sum:=(sqr(X[i])-2*X[i])/L(x);
  F:=sum
end;
 
var
  X:mas;
  i:integer;
  g:real;
begin
  writeln('Massiv X');
  randomize;
  for i:=1 to n do
  begin
    X[i]:=random(20)-10;
    write(X[i]:3);
  end;
  writeln;
  g:=F(X);
  writeln('g=',g:0:2);
end.

Полезно ли:

15   голосов , оценка 4.133 из 5

1 / 1 / 1

Регистрация: 10.12.2015

Сообщений: 91

1

15.03.2016, 20:44. Показов 5097. Ответов 2


Задание. Написать программу решения задачи, используя функции: в основной функции вычислить с помощью генератора случайных чисел 10 элементов массива, во вспомогательной — вычислить скалярную величину.
Проблема в том что я не смог сделать правильно задание на Паскале.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cmath>
const int n = 10;
float X[n];
double sum();
double Pr();
using namespace std;
int main()
{
cout << "Massiv X" << endl;
for (int i = 0; i < n; i++)
{
X[i] = rand() % 20 + sin(i) - 9;
cout << X[i] << " "; }
cout << endl;
double g;
{ g =sum();
cout << "g= " << g << endl; }
}
double sum()
{   double S = 0;
for (int i = 1; i < n; i++)
S += pow(X[i],2)-2*X[i]/Pr();
return S;
}
double Pr()
{   double P = 1; int i;
for (int k = 1; k < i; k++)
P *= (1+fabs(X[k]));
return P;
}

Программа нормально работает

Код

Massiv X
-6 -2.15853 8.9093 6.14112 3.2432 5.04108 -3.27942 3.65699 0.989358 -7.58788 
g= 210.451

На паскале:

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
uses math;
const n = 10;
type mas=array[1..n] of integer;
function F(X:mas):real;
function L(X:mas):real;
var i,sum:integer;
Pr:real;
begin
sum:=0;
for i:=1 to n do
sum:=(power(X[i],2)-2*X[i])/L(x);
F:=sum
end;
begin
Pr:=1;
for i:=1 to n do
Pr:=(1+abs(X[i]));
L:=Pr
end;
var X:mas;
    i:integer;
    g:real;
begin
writeln('Massiv X');
randomize;
for i:=1 to n do
 begin
  X[i]:=random(20)-10;
  write(X[i]:3);
 end;
writeln;
 begin
  g:=F(X);
  writeln('g=',g:0:2);
 end;
end.

Код

prog.pas(12,28) Error: Incompatible types: got "Extended" expected "SmallInt"
prog.pas(16,3) Error: Identifier not found "Pr"
prog.pas(17,6) Error: Identifier not found "i"
prog.pas(17,5) Error: Ordinal expression expected
prog.pas(17,5) Error: Illegal counter variable
prog.pas(18,3) Error: Identifier not found "Pr"
prog.pas(18,15) Error: Identifier not found "i"
prog.pas(19,1) Error: Wrong number of parameters specified for call to "L"
prog.pas(20,1) Error: Identifier not found "Pr"

как это исправить ?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Hi, again.

Now I have a question about Incompatible Types message. I know what it means but idk why it appears in a program I have integers ONLY. Take a look please and explain me where the number becomes Extended and why? Thanks a lot.

Code (It may have more errors):
var
 ta,l,p,i,j,d2ta,d3ta,d2l,d3l,d2f,d3f,nf,nta,nl:integer;
 f,g:text;
begin
 assign(f,’daruri.in’);
 reset(f);
 read(f,ta);
 readln(f,l);
 close(f);
if frac(ta/2)=0 then inc(d2ta)
else if frac(ta/3)=0 then inc(d3ta)
 else for i:=4 to 32000 do
   if frac(ta/i)<>0 then continue
   else break;
if frac(l/2)=0 then inc(d2l)
else if frac(l/3)=0 then inc(d3l)
 else for j:=4 to 32000 do
   if frac(l/j)<>0 then continue
   else break;
if d2ta<=d2l then if d2ta=0 then d2f:=1 else d2ta:=d2f
 else d2l:=d2f;
if d3ta<=d3l then if d3ta=0 then d3f:=1 else d3ta:=d3f
 else d3l:=d3f;
if i<=j then i:=nf
 else j:=nf;
p:=d2f*d3f*nf;
nta:=ta/p;
nl:=l/p;
 assign(g,’daruri.out’);
 rewrite(g);
 writeln(g,p);
 write(g,nta);
 write(g,nl);
 close(g);
end.

Error message:
s(27,8)Error: Incompatible types: got «Extended» expected «SmallInt»
s(28,6)Error: Incompatible types: got «Extended» expected «SmallInt»
s(41)Fatal: There were 2 errors compiling module, stopping
s(0)Fatal: Compilation aborted
                                                                      Thanks again, nice community. HaVe A nIcE dAy :) :) :) :)

    program ideone;
    const m = 7;
    const n = 5;
    var  x:Real;
    var  y:Real;
    var  z:Real;
    var  q:Real;
    var  r:Real;

    procedure  multiply();
    var a:Real;
    var b:Real;
    begin  a := x;  b := y;  z := 0;
      while b > 0 do
        begin  
          if odd(Qword(b)) then z := z + a;
          writeln('x');
          a := 2*a;  
          b := b/2;
        end
    end;

    begin 
      x := m;  y := n;  
      multiply();
      writeln(z);
    end.

Procedure “multiply” is used to calculate the product of two number.But it seems that a dead loop will appear and keep print «x» when the program is running.

Maybe it’s because the type of «b» is «Real», so the line «b = b/2» can never cause the var «b» less than or equal to 0, while «b <= 0» is the exit of the loop.

So I change the type of b ti Integer hoping that b / 2 can cause b to 0 when b is Integer.

    program ideone;
    const m = 7;
    const n = 5;
    var  x:Integer;
    var  y:Integer;
    var  z:Integer;
    var  q:Integer;
    var  r:Integer;

    procedure  multiply();
    var a:Integer;
    var b:Integer;
    begin  a := x;  b := y;  z := 0;
      while b > 0 do
        begin  
          if odd(Qword(b)) then z := z + a;
          writeln('x');
          a := 2*a;  
          b := b/2;
        end
    end;

    begin 
      x := m;  y := n;  
      multiply();
      writeln(z);
    end.

Then I meet another problem:

test.pas(19,13) Error: Incompatible types: got "Extended" expected "SmallInt"

To solve this problem, I add a cast to line «b = b/2»

 b := Integer(b/2);

but another error occur:

test.pas(19,12) Error: Illegal type conversion: "Extended" to "SmallInt"

What should I do to solve this series problem.

Содержание

  1. Почему выдаёт ошибку? Где я накосячила? Ошибка: unit1.pas(120,5) Fatal: Syntax error, «;» expected but «ELSE» found
  2. Fatal: Syntax error, «.» expected but «;» found
  3. 1 Answer 1
  4. Pascal Help ? 6 errors that I do not know how to fix
  5. TacticalMaestro
  6. [Паскалъ] Need Help
  7. Why does syntax error appear after running code?
  8. 1 Answer 1

Почему выдаёт ошибку? Где я накосячила? Ошибка: unit1.pas(120,5) Fatal: Syntax error, «;» expected but «ELSE» found

procedure TForm1.RadioButton1Change(Sender: TObject);
begin
if radiobutton1.checked then
begin
edit1.text := IntToStr(Bin2Dec(edit1.text));
CS := 10;
s:=edit1.text
end;
else begin
edit1.text := IntToStr(Oct2Dec(edit1.text));
CS := 10;
s:=edit1.text;

Button1.Enabled:=True;
Button2.Enabled:=True;
Button3.Enabled:=True;
Button4.Enabled:=True;
Button5.Enabled:=True;
Button6.Enabled:=True;
Button7.Enabled:=True;
Button8.Enabled:=True;
Button9.Enabled:=True;
Button10.Enabled:=True;
Button11.Enabled:=True;
Button12.Enabled:=True;
Button13.Enabled:=True;
Button15.Enabled:=True;
Button16.Enabled:=True;
Button17.Enabled:=True;
Button18.Enabled:=True;
Button14.Enabled:=True;
Button19.Enabled:=True;
Button20.Enabled:=True;
Button21.Enabled:=True;
Button22.Enabled:=True;
Button23.Enabled:=True;
end;

—-исходный кусок ————
CS := 10;
s:=edit1.text
end;
else begin
————неправильно, д. б. так ——————-
CS := 10;
s:=edit1.text;
end
else begin

З. Ы. внимательнее с синтаксисом. лучше код форматировать отступами, вроде так:
begin
begin
.
end;
end;
сразу ясно какой энд какому бегину принадлежит )))

Источник

Fatal: Syntax error, «.» expected but «;» found

1 Answer 1

The reason for this is that your begin s and end s are not balanced; disregarding the opening begin and closing end. for the program’s syntax to be correct, you should have equal numbers of each, but you have 4 begin s and 8 end s.

Obviously, your code is to compute the solutions of a quadratic equation. What I think you should do is to adjust the layout of your code so that it reflects that and then correctly the begin s and end s. In particular, your program is trying to detect whether any of a, b and d is zero and, if so, write a diagnostic message, otherwise calculate the roots by the usual formula.

Unfortunately, your begin s and end s do not reflect that. Either the whole of the block starting d := . needs to be executed or none of it does, so the else on the line before needs to be followed by a begin , as in

(You don’t say which Pascal compiler you are using, but the above fixes two points which are flagged as errors in FreePascal.

If you need more help than that, please ask in a comment.

Btw, there are some grammatical constructs in Pascal implementations where an end can appear without a matching preceding begin such as case . of . end .

Источник

Pascal Help ? 6 errors that I do not know how to fix

TacticalMaestro

Estimable

Program TypeofCreditCard;
Var
AppliName: array[1..99] of String;
SSnum: array[1..99] of Integer;
GSal: array[1..99] of Integer;
TSalD: array[1..99] of Integer;

Name, CC : String;
Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ;

Begin
Writeln ( ‘Enter applicants who applied for a type of credit card’);
Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco. ;

While ( Name <> ‘ Stop ‘ ) do
Begin
NS:= GS-TSD ;
Sum:= Exp + Rep ;
PofIncome:=(NS * 0.45);
Begin
If ( GS >4000) AND ( CC = ‘Bronze Card’ ) then
YS:= GS * 12 ;
C_Amt := YS * 0.25;
i:= i + 1;
AppliName := Name;
SSNum := SSN ;
GSal [ i]:= GS ;
TSalD := TSD ;
End ;
Begin
If (GS >= 7500) AND [CC= ‘Gold Card’] then
YS:= GS * 12 ;
C_Amt:= YS * 0.3;
i:= i + 1 ;
AppliName := Name;
SSnum:=SSN;
GSal:=GS;
TSalD:=TSD;
End;
Begin
If (GS>=10,000) AND ( CC = ‘ Platinum Card’) then
YS := GS * 12;
C_Amt: = YS * 0.4;
i:= i + 1;
A ppliName := Name;
SSNum := SSN;
GSal :=GS;
TSalD := TSD;

End if
End if
End if
End While
End.

The five errors are :
1. Error:Incompatible types: got «Boolean» expected «LongInt» — For this line : If (GS >= 7500) AND [CC= ‘Gold Card’] then

2.Error:Incompatible types: got » Set of Boolean» expected » LongInt» — for the same line (If (GS >= 7500) AND [CC= ‘Gold Card’] then )

3.Error:Incompatible types: got «single» expected «smallint» — for C_Amt := YS * 0.25 ; in Bronze Card

4.Error:Incompatible types: got «extended» expected «smallint» for C_Amt := YS * 0.3; in Gold Card

5.Fatal:syntax error , «)» expected but «,» found — (If GS >= 10000) AND [CC= ‘Platinum’] then )

Thanks for any help. I know my program is by no means perfect because I am awful at Pascal and desperately need help on fixing these things. So I am open to anything that will get this program running in Pascal. Thanks.

Источник

[Паскалъ] Need Help

Что программа должна делать(на пхп)

ЕМНИП перед else там точка с запятой не ставится.

Не, ругается на другое, и спасибо это пофиксил.

> перед else там точка с запятой не ставится.

> ругается на другое

Условия в скобки попробуй.

Перед else ; не ставится.

У readln точно такой синтаксис? (я уже запамятовал)

Условия в скобки не надо?

Операции сравнения в скобки возьми.

А теперь, дружище, запомни, что вот этот выхлоп

untitled.pas(26,7) Error: Incompatible types: got «Boolean» expected «LongInt»
untitled.pas(28,2) Fatal: Syntax error, «;» expected but «ELSE» found

должен читать ТЫ сам, а не ЛОР.

Свободно говорю на Русском, Литовском, Английском.

Свободно говорю на Английском

Error: Incompatible types: got «Boolean» expected «LongInt»

Fatal: Syntax error, «;» expected but «ELSE» found

Источник

Why does syntax error appear after running code?

presently learning how to code in pascal and vba. Assisting my daughter who is preparing for examinations next year. I am stuck on a problem concerning her present assignment. After running the code the following errors were received:

main.pas(1,2) Fatal: Syntax error, «BEGIN» expected but «identifier N» found Fatal: Compilation aborted

Tried fixing the code, but as i said I have just started learning to code.

The expected result is to choose a candidate by his ID number which would lead to his name, the number of vote available in a district and the number of votes the candidate obtained being displayed. it would then result in a calculation between the two vote counts (division) and if the percentage is greater than 20% he would receive a refund, if less than 20% he would not receive a refund. either result should be displayed.

1 Answer 1

I’m afraid that you q, as it currently stands, isn’t really suited to SO because SO is really about specific (single) programming problems, not incrementally debugging source code (see Sertac’s comment), nor providing online tutorials, which I think you probably need at this point. And I feel rather uncomfortable about posting this as an answer, because it isn’t one in the normal SO sense. However it seems to me that you could use a few pointers:

Unless you absolutely have to use the online compiler, download and use a free online one like Free Pascal, which is well supported, uses standard Pascal syntax, and I’m sure there are basic first-time tutorials available. See here to download Lazarus, which is an excellent IDE for Free Pascal (which is included in the install) and here for an introductory tutorial.

Secondly, there are structural and syntactic elements of your source-code which are definitely not standard Pascal, in particular endif and elseif . Another example is that in standard Pascal, you have to surround a string (like your Richards, etc) with single-quotes ‘ , not precede the string by a back-quote. This is very possibly the cause of your «illegal character» error

For a decent Free Pascal introductory tutorial see here and this youtube tutorial, both found by googling

«free pascal» introductory tutorial.

Fourthly, your online compiler ought to be complaining about the endif abd elseif s, the incorrectly string formatting and the fact that several of your variables are duplicated ( DV and VR used as the names of an integer variable and an array, for example as in Pascal, identifiers within the same ‘scope’ need to have unique names (the fact that I should explain what ‘scope’ means is a sign that what the q needs is a tutorial).

Источник

avatar
h18

05 Oct 2014 в 18:28

h18

Пользователь

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

h18

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

Не могу разобраться с одним заданием, если разбираетесь в программке — кому не лень, помогите, пожалуйста.
Задание звучит: написать соответственно прогу, которая определяет кол-во твоих денег. Ты положил в банк N денег, под P процентов в год, на G лет. Ну и программка определяет кол-во твоих денег через G лет.
Заранее, кто решился отозваться —  большое спасибо. Можно в личку, можно прямо тут.

Sexy.Bamboe

Пользователь

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Sexy.Bamboe

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Я тебе просто формулу напишу, так как паскаль не знаю, а синтаксис лень гуглить:
N*(1+P/100.0)^G

h18

Пользователь

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

h18

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

Sexy.Bamboe сказал(а):↑

Я тебе просто формулу напишу, так как паскаль не знаю, а синтаксис лень гуглить:
N*(1+P/100.0)^G

Нажмите, чтобы раскрыть…

я формулу знал эту, подставлял как мог ее, не получилось, вот поэтому и решил написать, дескать кто-то сможет написать без ошибок. Если точнее, то он выдает got «extended» expected «smallint». ;D

Sexy.Bamboe

Пользователь

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Sexy.Bamboe

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

h18 сказал(а):↑

я формулу знал эту, подставлял как мог ее, не получилось, вот поэтому и решил написать, дескать кто-то сможет написать без ошибок. Если точнее, то он выдает got «extended» expected «smallint». ;D

Нажмите, чтобы раскрыть…

лучше код скинь. где-то проблемы с типами

Селестия

Пользователь

Регистрация:
05.01.2014

Сообщения: 2079

Рейтинг: 3958

Селестия

Регистрация:
05.01.2014

Сообщения: 2079

Рейтинг: 3958

var n,p,g,x,y
readln(n,p,g);
x:=N/100*P*G;
y:=N+x;
writeln(y);
end.
Так??

Dockerok

Пользователь

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Dockerok

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Скинь код, а то последний раз в паскале работал лет 8 назад

Топ Булочка

Пользователь

Регистрация:
30.07.2014

Сообщения: 290

Рейтинг: 179

Топ Булочка

Регистрация:
30.07.2014

Сообщения: 290

Рейтинг: 179

FromTheBottom

Пользователь

Регистрация:
09.09.2014

Сообщения: 1384

Рейтинг: 965

FromTheBottom

Регистрация:
09.09.2014

Сообщения: 1384

Рейтинг: 965

Поменяй целочисленные переменные на вещественные. У тебя в этом ошибка

h18

Пользователь

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

h18

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

program ceturtaisuzd;
uses crt;
var a,b,n,p,g:integer;
       begin
       clrscr;
       writeln(‘Cik ir tavs sakuma kapitals?’);
       readln(n);
       writeln(‘Uz cik gadiem gribi atstat naudu?’);
       readln(g);
       writeln(‘Uz kadu procentu likmi gribi atstat?’);
       readln(p);
       a:=0;
       a:=n*(1+p/100);
       readln(a);
       writeln(‘Sanac ka tavs kapitals bus’ ,a);
       readln;
       end.

Dockerok

Пользователь

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Dockerok

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

AngryShutty сказал(а):↑

var n,p,g,x,y
readln(n,p,g);
x:=N/100*P*G;
y:=N+x;
writeln(y);
end.
Так??

Нажмите, чтобы раскрыть…

явно не так, нет объявления типов данных

h18

Пользователь

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

h18

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

Sexy.Bamboe сказал(а):↑

лучше код скинь. где-то проблемы с типами

Нажмите, чтобы раскрыть…

В скобках там вопросы на другом языке, они значения не имеют)

Dockerok

Пользователь

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Dockerok

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

h18 сказал(а):↑

program ceturtaisuzd;
uses crt;
var a,b,n,p,g:integer;
       begin
       clrscr;
       writeln(‘Cik ir tavs sakuma kapitals?’);
       readln(n);
       writeln(‘Uz cik gadiem gribi atstat naudu?’);
       readln(g);
       writeln(‘Uz kadu procentu likmi gribi atstat?’);
       readln(p);
       a:=0;
       a:=n*(1+p/100);
       readln(a);
       writeln(‘Sanac ka tavs kapitals bus’ ,a);
       readln;
       end.

Нажмите, чтобы раскрыть…

лол
у тебя же а — целочисленный, а ты присваеваешь дробь…
сделай a:real

да и вообще у тебя програ не правилоно написанная

TypickalRak

Пользователь

Регистрация:
13.10.2013

Сообщения: 113

Рейтинг: 64

TypickalRak

Регистрация:
13.10.2013

Сообщения: 113

Рейтинг: 64

h18 сказал(а):↑

program ceturtaisuzd;
uses crt;
var a,b,n,p,g:integer(целый тип данных); extended(дробный тип данных, он тебе нужен)
       begin
       clrscr;
       writeln(‘Cik ir tavs sakuma kapitals?’);
       readln(n);
       writeln(‘Uz cik gadiem gribi atstat naudu?’);
       readln(g);
       writeln(‘Uz kadu procentu likmi gribi atstat?’);
       readln(p);
       a:=0;
       a:=n*(1+p/100);
       readln(a);
       writeln(‘Sanac ka tavs kapitals bus’ ,a);
       readln;
       end.

Нажмите, чтобы раскрыть…

В паскале операция деления через / работает только для вещественных типов данных: extended, real… (они представляют числа в виде десятичных дробей)

TYZzzz

Пользователь

Регистрация:
17.01.2013

Сообщения: 941

Рейтинг: 401

TYZzzz

Регистрация:
17.01.2013

Сообщения: 941

Рейтинг: 401

h18 сказал(а):↑

program ceturtaisuzd;
uses crt;
var a,b,n,p,g:integer;
       begin
       clrscr;
       writeln(‘Cik ir tavs sakuma kapitals?’);
       readln(n);
       writeln(‘Uz cik gadiem gribi atstat naudu?’);
       readln(g);
       writeln(‘Uz kadu procentu likmi gribi atstat?’);
       readln(p);
       a:=0;
       a:=n*(1+p/100);
       readln(a);
       writeln(‘Sanac ka tavs kapitals bus’ ,a);
       readln;
       end.

Нажмите, чтобы раскрыть…

Последний readln(» «) поставь. И с clscr не всегда работает.

Sexy.Bamboe

Пользователь

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Sexy.Bamboe

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Да, короче для переменной, которая сумму всю хранить будет нужен вещественный тип. Для переменной которую на 100 делишь тоже или дели на 100.0

Dockerok

Пользователь

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Dockerok

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

program ceturtaisuzd;
uses crt;
var a: real;
     count,b,n,p,g:integer;
begin
clrscr;
writeln(‘Cik ir tavs sakuma kapitals?’);
readln(n);
writeln(‘Uz cik gadiem gribi atstat naudu?’);
readln(g);
writeln(‘Uz kadu procentu likmi gribi atstat?’);
readln(p);
a:=n;
for count:=1 to g do
a:=a+(n*(1+p/100));

readln(a);
writeln(‘Sanac ka tavs kapitals bus’ ,a);
readln;
end.

в идеале как-то так должно быть

Helfer

Пользователь

Регистрация:
02.03.2014

Сообщения: 458

Рейтинг: 247

Helfer

Регистрация:
02.03.2014

Сообщения: 458

Рейтинг: 247

AngryShutty сказал(а):↑

var n,p,g,x,y
readln(n,p,g);
x:=N/100*P*G;
y:=N+x;
writeln(y);
end.
Так??

Нажмите, чтобы раскрыть…

x:=Power(N/100*P,G)
вродь возведение так делается

TYZzzz

Пользователь

Регистрация:
17.01.2013

Сообщения: 941

Рейтинг: 401

TYZzzz

Регистрация:
17.01.2013

Сообщения: 941

Рейтинг: 401

Helfer сказал(а):↑

x:=Power(N/100*P,G)
вродь возведение так делается

Нажмите, чтобы раскрыть…

Pow() вроде функция.

Helfer

Пользователь

Регистрация:
02.03.2014

Сообщения: 458

Рейтинг: 247

Helfer

Регистрация:
02.03.2014

Сообщения: 458

Рейтинг: 247

TYZzzz сказал(а):↑

Pow() вроде функция.

Нажмите, чтобы раскрыть…

Да я уже года 2 не кодил после универа) Вроде ты прав) у меня по этим языкам такая мешанина в голове: лисп, пролог, паскаль, С++… а толком то ничего и не выучил =)

noob.cfg

Пользователь

Регистрация:
19.08.2014

Сообщения: 55

Рейтинг: 64

noob.cfg

Регистрация:
19.08.2014

Сообщения: 55

Рейтинг: 64

лiл если ты элементарное не знаеш зачем ты учишься на программиста -_-
меняй вуз иди на дворника

Dockerok

Пользователь

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

Dockerok

Регистрация:
30.06.2013

Сообщения: 45

Рейтинг: 7

noob.cfg сказал(а):↑

лiл если ты элементарное не знаеш зачем ты учишься на программиста -_-
меняй вуз иди на дворника

Нажмите, чтобы раскрыть…

он не обязательно учится на программиста. На специальности экономика-кибернетика тоже есть паскаль.

Hy6o_Hy6

Пользователь

Регистрация:
16.11.2013

Сообщения: 3531

Рейтинг: 2188

Hy6o_Hy6

Регистрация:
16.11.2013

Сообщения: 3531

Рейтинг: 2188

h18 сказал(а):↑

Не могу разобраться с одним заданием, если разбираетесь в программке — кому не лень, помогите, пожалуйста.
Задание звучит: написать соответственно прогу, которая определяет кол-во твоих денег. Ты положил в банк N денег, под P процентов в год, на G лет. Ну и программка определяет кол-во твоих денег через G лет.
Заранее, кто решился отозваться —  большое спасибо. Можно в личку, можно прямо тут.

Нажмите, чтобы раскрыть…

если ты это не можешь сам решить, то пора удалять доту, мозочки то с орешек.

Dahz

Пользователь

Регистрация:
25.09.2012

Сообщения: 1062

Рейтинг: 423

Dahz

Регистрация:
25.09.2012

Сообщения: 1062

Рейтинг: 423

noob.cfg сказал(а):↑

лiл если ты элементарное не знаеш зачем ты учишься на программиста -_-
меняй вуз иди на дворника

Нажмите, чтобы раскрыть…

Попробуй потоньше.

h18

Пользователь

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

h18

Регистрация:
14.08.2014

Сообщения: 122

Рейтинг: 70

Dockerok сказал(а):↑

program ceturtaisuzd;
uses crt;
var a: real;
     count,b,n,p,g:integer;
begin
clrscr;
writeln(‘Cik ir tavs sakuma kapitals?’);
readln(n);
writeln(‘Uz cik gadiem gribi atstat naudu?’);
readln(g);
writeln(‘Uz kadu procentu likmi gribi atstat?’);
readln(p);
a:=n;
for count:=1 to g do
a:=a+(n*(1+p/100));

readln(a);
writeln(‘Sanac ka tavs kapitals bus’ ,a);
readln;
end.

в идеале как-то так должно быть

Нажмите, чтобы раскрыть…

Почти верно, но после того, как вводишь n,p,g в программу он не хочет считать дальше. а так compile работает все ок ;)

Sexy.Bamboe

Пользователь

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

Sexy.Bamboe

Регистрация:
10.09.2014

Сообщения: 391

Рейтинг: 240

noob.cfg сказал(а):↑

лiл если ты элементарное не знаеш зачем ты учишься на программиста -_-
меняй вуз иди на дворника

Нажмите, чтобы раскрыть…

школьное же задание, лол, сам иди на дворника)

Тема закрыта

  • Заголовок

    Ответов Просмотров

    Последнее сообщение

  • ДомашнийМальчик

    Сообщений: 14
    09 Feb 2023 в 16:47

    Сообщений:14

    Просмотров:20

    ДомашнийМальчик

  • Tromboni

    Сообщений: 9
    09 Feb 2023 в 16:37

    Сообщений:9

    Просмотров:17

    Mandelli

  • Kujivunia

    Сообщений: 5
    09 Feb 2023 в 16:35

    Сообщений:5

    Просмотров:12

    Kujivunia

  • Adler34

    Сообщений: 10
    09 Feb 2023 в 16:10

    Сообщений:10

    Просмотров:25

    KeltZer

  • Никита Тимченко

    Сообщений: 7
    09 Feb 2023 в 16:10

    Сообщений:7

    Просмотров:19

    Mash1nka

В этом разделе описаны все ошибки, которые могут случиться при проверке типов.

Сообщение

Описание

Error: Type mismatch

Это может произойти во многих случаях:

Назначенная вами переменная отличается от типа, который используется в выражении

Вы вызываете функцию или процедуру с параметрами, которые несовместимы с параметрами в объявлении функции или процедуры

Error: Incompatible types: got «Сообщ1» expected «Сообщ2»

Невозможно преобразование между двумя типами. Ещё одна причина – типы объявлены в разных объявлениях:

Var A1 : Array[1..10] Of Integer;
  A2 : Array[1..10] Of Integer;
Begin
A1:=A2; {Этот оператор также даёт такую ошибку, потому
          что выполняется строгая проверка типов Pascal}
End.

Error: Type mismatch between «Сообщ1» and «Сообщ2»

Типы не являются эквивалентными.

Error: Type identifier expected

Идентификатор не является типом, или вы забыли указать идентификатор type.

Error: Variable identifier expected

Это случается, если вы помещаете константу в процедуру (такую как Inc или Dec), в то время как процедура требует переменной. Для таких процедур в качестве параметров можно помещать только переменные.

Error: Integer expression expected, but got «Сообщение»

Компилятор ожидает выражения типа integer, но получает другой тип.

Error: Boolean expression expected, but got «Сообщение»

Выражение должно быть типа boolean. Оно должно возвращать True или False.

Error: Ordinal expression expected

Выражение должно быть порядкового типа, то есть максимум типа Longint. Эта ошибка случается, например, если вы указали второй параметр процедуры Inc или Dec, который не соответствует порядковому типу.

Error: pointer type expected, but got «Сообщение»

Переменная или выражения не являются указателем. Это случается, если вы помещаете переменную, которая не является указателем, в New или Dispose.

Error: class type expected, but got «Сообщение»

Переменная или выражение не являются типом class. Это обычно случается, если

1.Родительский класс в объявлении класса не является классом

2.Обработчик исключения (On) cсодержит идентификатор типа, который не является классом.

Error: Can’t evaluate constant expression

Эта ошибка может случиться, если границы объявленного вами массива не обозначены порядковыми константами.

Error: Set elements are not compatible

Вы пытаетесь выполнить операцию с двумя множествами, в то время как типы элементов этих множеств не являются одинаковыми. Базовые типы множеств должны быть одинаковыми при объединении.

Error: Operation not implemented for sets

Некоторые бинарные операторы не определены для множеств. Это операторы: div, mod, **, >= и <=. Последние два могут быть определены для множеств в будущих версиях.

Warning: Automatic type conversion from floating type to COMP which is an integer type

Обнаружено явное преобразование типов из real в comp. s encountered. Поскольку comp – это 64-битное целое число, то это может вызвать ошибку.

Hint: use DIV instead to get an integer result

Если подсказки включены, то целочисленное деление с оператором ‘/‘ приведёт к этому сообщению, потому что результатом будет вещественный тип.

Error: string types doesn’t match, because of $V+ mode

Если выполняется компиляция в режиме {$V+}, то строка, передаваемая вами в качестве параметра, должна быть точно такого же типа, как параметр процедуры.

Error: succ or pred on enums with assignments not possible

Если вы объявили перечисляемый тип в стиле С, например, так:

Tenum = (a,b,e:=5);

То вы не сможете использовать функции Succ или Pred с этим перечислением.

Error: Can’t read or write variables of this type

Вы пытаетесь прочитать или записать переменную из файла или в файл текстового типа, который не поддерживает тип переменной. Только целочисленные типы, вещественные, pchars и strings можно читать из файла или записывать в текстовый файл. Логические переменные можно только записывать в текстовый файл.

Error: Can’t use readln or writeln on typed file

readln и writeln можно использовать только с текстовыми файлами.

Error: Can’t use read or write on untyped file.

read и write допускаются только для текстовых или типизированных файлов.

Error: Type conflict between set elements

Это означает, что не менее одного элемента множества имеют неправильный тип.

Warning: lo/hi(dword/qword) returns the upper/lower word/dword

Free Pascal поддерживает перегруженную версию lo/hi для longint/dword/int64/qword, которые возвращают наименьшее/наибольшее (результат типа слово/двойное слово) значение аргумента. Turbo Pascal позволяет использовать 16-битные lo/hi, которые возвращают биты 0..7 для lo и биты 8..15 для hi. Если вы хотите получить поведение, аналогичное Turbo Pascal, вы должны использовать приведение типов к word или integer.

Error: Integer or real expression expected

Первый аргумент для str должен быть типа real или integer.

Error: Wrong type «Сообщение» in array constructor

Вы пытаетесь использовать тип в конструкторе массива, который недопустим.

Error: Incompatible type for arg no. Сообщ1: Got «Сообщ2», expected «Сообщ3»

Вы пытаетесь передать неправильный тип в указанный параметр.

Error: Method (variable) and Procedure (variable) are not compatible

Вы не можете связать метод с процедурной переменной или процедуру с указателем на метод.

Error: Illegal constant passed to internal math function

Аргумент-константа, переданный в функцию ln или sqrt выходит за пределы диапазона для этой функции.

Error: Can’t take the address of constant expressions

Невозможно получить адрес выражения-константы, потому что оно не записывается в память. Вы можете попробовать сделать типизированную константу. Эта ошибка может также появиться, если вы пытаетесь поместить свойство в параметр var.

Error: Argument can’t be assigned to

Только выражение, которое может быть в левой части присваивания, может быть передано как вызов по ссылке аргумента. Примечание: Свойства могут использоваться в левой части присваивания, тем не менее, они не могут использоваться как аргументы.

Error: Can’t assign local procedure/function to procedure variable

Не допускается присваивать локальные процедуры/функции процедурным переменным, потому что соглашение о вызовах локальных процедур/функций отличаются. Вы можете только присвоить локальную процедуру/функцию пустому указателю.

Error: Can’t assign values to an address

Не допускается присваивать значение адресу переменной, константы, процедуры или функции. Вы можете попытаться выполнить компиляцию с опцией -So, если идентификатор является процедурной переменной.

Error: Can’t assign values to const variable

Не допускается присваивать значение переменной, которая объявлена как константа. Обычно параметр объявляется как константа. Чтобы иметь возможность изменять значение, передавайте параметр по значению или параметр по ссылке (используя var).

Error: Array type required

Если вы хотите получить доступ к переменной, используя индекс ‘[<x>]‘, то тип должен быть массивом. В режиме FPC указатель также допускается.

Error: interface type expected, but got  «»Сообщение»

Компилятор ожидал для нумератора имя типа интерфейса, но получил нечто другое. Следующий код приведёт к этой ошибке:

Type
TMyStream = Class(TStream,Integer)

Hint: Mixing signed expressions and longwords gives a 64bit result

Если вы делите (или вычисляете модуль) выражения со знаком с типом longword (или наоборот), или если вы имеете переполнение и/или включена проверка диапазона и используется арифметическое выражение (+, -, *, div, mod), в котором оба числа со знаком и появляется longwords, то всё это вычисляется как 64-битная арифметическая операция, которая медленнее, чем обычная 32-битная. Вы можете избежать этого при помощи преобразования типа одного из операндов в подходящий для результата и другого операнда.

Warning: Mixing signed expressions and cardinals here may cause a range check error

Если вы используете бинарный оператор (and, or, xor) и один из операндов — это longword, в то время как другой – это выражение со знаком, то, если проверка диапазона включена, вы можете получить ошибку проверки диапазона, потому что в этом случае оба операнда преобразуются в longword перед выполнением операции. Вы можете избежать этого при помощи преобразования типа одного из операндов в подходящий для результата и другого операнда.

Error: Typecast has different size (Сообщ1 -> Сообщ2) in assignment

Преобразование типа при отличающихся размерах не допускается, когда переменная используется в присваивании.

Error: enums with assignments can’t be used as array index

Если вы объявили перечисляемый тип, который имеет С-подобные присваивания, как показано ниже:

Tenum = (a,b,e:=5);

Вы не можете использовать его как индекс массива.

Error: Class or Object types «Сообщ1» and «Сообщ2» are not related

Выборка из одного класса в другой, в то время как класс/объект не являются связанными. Вероятно, это ошибка ввода.

Warning: Class types «arg1» and «arg2» are not related

Выборка из одного класса в другой, в то время как класс/объект не являются связанными. Вероятно, это ошибка ввода.

Error: Class or interface type expected, but got «arg1»

Компилятор ожидал имя класса или интерфейса, но получил другой тип или идентификатор.

Error: Type «Сообщение» is not completely defined

Эта ошибка случается, если тип не завершён, например, тип pointer, который указывает на неопределённый тип.

Warning: String literal has more characters than short string length

Размер строки-константы, которая связана с shortstring, больше максимального размера для shortstring (255 символов).

Warning: Comparison is always false due to range of values

Это сравнение беззнакового значения и константы со знаком, которая меньше нуля. По причине преобразования оператор всегда будет возвращать FALSE. Выполните явное преобразование константы в правильный диапазон, чтобы избежать этой проблемы.

Warning: Comparison is always true due to range of values

Это сравнение беззнакового значения и константы со знаком, которая меньше нуля. По причине преобразования оператор всегда будет возвращать TRUE. Выполните явное преобразование константы в правильный диапазон, чтобы избежать этой проблемы.

Warning: Constructing a class «Сообщ1» with abstract method «Сообщ2»

Например, создаваемый класс содержит неисполняемые абстрактные методы. Имеется вероятность, что случится ошибка времени исполнения 211 в коде, если эта процедура будет когда-либо вызвана. Все абстрактные методы должны быть перегружаемыми.

Hint: The left operand of the IN operator should be byte sized

Левый операнд в операторе IN не является порядковым или перечислением, который помещается в 8 бит. Это может привести к ошибке проверки диапазона. На текущий момент оператор in поддерживает левый оператор только в пределах байта. В случае с перечислениями, размер элемента перечисления может изменяться опциями {$PACKENUM} или {$Zn}.

Warning: Type size mismatch, possible loss of data / range check error

Это случается, когда меньшему типу присваивается значение, большее, чем исходный тип. Это означает, что может произойти ошибка проверки диапазона или уменьшение значения.

Hint: Type size mismatch, possible loss of data / range check error

Это случается, когда меньшему типу присваивается значение, большее, чем исходный тип. Это означает, что может произойти ошибка проверки диапазона или уменьшение значения.

Error: The address of an abstract method can’t be taken

Не найдено тело абстрактного метода, поэтому адрес абстрактного метода не может быть назначен.

Error: Assignments to formal parameters and open arrays are not possible

Вы пытаетесь присвоить значение формальному параметру (нетипизированный var, const или out), или открытому массиву.

Error: Constant Expression expected

Компилятор ожидал выражение-константу, но получил выражение- переменную.

Error: Operation «Сообщ1» not supported for types «Сообщ2» and «Сообщ3»

Операция не допускается для указанных типов.

Error: Illegal type conversion: «Сообщ1» to «Сообщ2»

Когда выполняете преобразование типов, вы должны понимать, что размеры переменной и типа назначения одинаковы.

Hint: Conversion between ordinals and pointers is not portable

Если вы преобразуете тип pointer в longint (или наоборот), то код не будет компилироваться на машинах, использующих 64-разрядную адресацию.

Warning: Conversion between ordinals and pointers is not portable

Если вы преобразуете тип pointer в порядковый тип с другим размером (или наоборот), то могут возникнуть проблемы. Это предупреждение помогает в поиске 32-битного специального кода, где cardinal/longint используются для преобразования указателей в порядковые типы. Решением проблемы является использование вместо этого типов ptrint/ptruint.

Error: Can’t determine which overloaded function to call

Вы вызываете перегруженную функцию с параметром, который не связан с каким-либо объявленным списком параметров, например, когда вы имеете объявленную функцию с параметрами word и longint, а затем вызываете её с параметром типа integer.

Error: Illegal counter variable

Переменная для цикла for должна быть порядкового типа. Переменные циклов не могут быть вещественными числами или строками.

Warning: Converting constant real value to double for C variable argument, add explicit typecast to prevent this.

В C значения вещественных констант по умолчанию имеют тип double. Из этих соображений, когда вы передаёте вещественную константу в функцию С в качестве параметра, компилятор FPC по умолчанию преобразует её в тип double. Если вы хотите контролировать этот процесс, добавьте для константы явное преобразование в нужный тип.

Error: Class or COM interface type expected, but got «Сообщение»

Некоторые операторы, такие как AS, применяются только для классов или COM-интерфейсов.

Error: Constant packed arrays are not yet supported

Вы не можете объявить битовый (упакованный) массив как типизированную константу.

Error: Incompatible type for arg no. Сообщ1: Got «Сообщ2» expected «(Bit)Packed Array»

Компилятор ожидает битовый (упакованный) массив как указанный параметр.

Error: Incompatible type for Сообщение no. Сообщ1: Got «Сообщ2» expected «»(not packed) Array»

Компилятор ожидает регулярный (то есть НЕ упакованный) массив как указанный параметр.

Error: Elements of packed arrays cannot be of a type which need to be initialised

Поддержка упакованных массивов, которым необходима инициализация (таких как ansistrings, или записей, содержащих ansistrings), пока не реализована.

Error: Constant packed records and objects are not yet supported

Вы не можете объявить битовый (упакованный) массив как типизированную константу в данное время.

Warning: Arithmetic «Сообщение» on untyped pointer is unportable to {$T+}, suggest typecast

Сложение/вычитание из нетипизированных указателей может работать по разному в {$T+}. Используёте преобразование типов для типизированных указателей.

Error: Can’t take address of a subroutine marked as local

Нельзя получить адрес подпрограммы, помеченной как локальная.

Error: Can’t export subroutine marked as local from a unit

Подпрограмма, помеченная как локальная, не может быть экспортирована из модуля.

Error: Type is not automatable: «Сообщение»

Только byte, integer, longint, smallint, currency, single, double, ansistring, widestring, tdatetime, variant, olevariant, wordbool и все интерфейсы являются automatable.

Hint: Converting the operands to «Сообщение» before doing the add could prevent overflow errors.

Сложение двух типов может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед сложением.

Hint: Converting the operands to «Сообщение» before doing the subtract could prevent overflow errors.

Вычитание между двумя типами может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед вычитанием.

Hint: Converting the operands to «Сообщение» before doing the multiply could prevent overflow errors.

Умножение между двумя типами может вызвать ошибку переполнения. Обычно вы конвертируете результат в больший тип. Вы должны предотвращать такие ошибки, преобразуя операнды в этот тип перед умножением.

Warning: Converting pointers to signed integers may result in wrong comparison results and range errors, use an unsigned

Виртуальное адресное пространство на виртуальных машинах располагается от $00000000 до $ffffffff. Многие операционные системы позволяют выделять память с адресами выше $80000000. Например, как WINDOWS, так и LINUX, допускают использование указателей в диапазоне от $0000000 до $bfffffff. Если вы преобразуете типы со знаком, это может вызвать ошибки переполнения и проверки диапазона, но также $80000000 < $7fffffff. Это может вызвать случайную ошибку в коде, подобно этому: «if p>q».

Error: Interface type Сообщение has no valid GUID

Если применяется оператор as для интерфейса или класса, то интерфейс (то есть правый операнд оператора as) должен иметь правильный GUID.

Error: Invalid selector name

Селектор Objective-C не может быть пустым, он должен быть правильным идентификатором или одинарным двоеточием, а если он содержит менее одного двоеточия, он также должен быть завершён.

Error: Expected Objective-C method, but got Сообщение

Селектор может быть создан только для методов Objective-C, не для любых других процедур/функций/методов.

Error: Expected Objective-C method or constant method name

Селектор может быть создан только для методов Objective-C, при задании имени используются строковые константы или идентификатор метода Objective-C, который является видимым из текущей области видимости.

Error: No type info available for this type

Информация о типах не генерируется для некоторых типов, таких как перечисления с пропусками в их диапазоне значений (включая перечисления, нижняя граница которых отлична от нуля).

Error: Ordinal or string expression expected

The expression must be an ordinal or string type.

Error: String expression expected

The expression must be a string type.

Warning: Converting 0 to NIL

Use NIL rather than 0 when initialising a pointer.

Error: Objective-C protocol type expected, but got ”arg1”

The compiler expected a protocol type name, but found something else.

Error: The type ”arg1” is not supported for interaction with the Objective-C runtime

Objective-C makes extensive use of run time type information (RTTI). This format is defined by the maintainers of the run time and can therefore not be adapted to all possible Object Pascal types. In particular, types that depend on reference counting by the compiler (such as ansistrings and certain kinds of interfaces) cannot be used as fields of Objective-C classes, cannot be directly passed to Objective-C methods, and cannot be encoded using objc_encode.

Error: Class or objcclass type expected, but got ”arg1”

It is only possible to create class reference types of class and objcclass

Error: Objcclass type expected

The compiler expected an objcclass type

Warning: Coerced univ parameter type in procedural variable may cause crash or memory corruption: arg1 to arg2

univ parameters are implicitly compatible with all types of the same size, also in procedural variable definitions. That means that the following code is legal, because single and longint have the same size:

{$mode macpas}

Type

  TIntProc = procedure (l: univ longint);

  procedure test(s: single);

    begin

      writeln(s);

    end;

  var

    p: TIntProc;

  begin

    p:=test;

    p(4);

  end.

This code may however crash on platforms that pass integers in registers and floating point values on the stack, because then the stack will be unbalanced. Note that this warning will not flagg all potentially dangerous situations. when test returns.

Error: Type parameters of specializations of generics cannot reference the currently specialized type

Recursive specializations of generics like Type MyType = specialize MyGeneric<MyType>; are not possible.

Error: Type parameters are not allowed on non-generic class/record/object procedure or function

Type parameters are only allowed for methods of generic classes, records or objects

Error: Generic declaration of ”arg1” differs from previous declaration

Generic declaration does not match the previous declaration

Error: Helper type expected

The compiler expected a class helper type.

Error: Record type expected

The compiler expected a record type.

Error: Derived class helper must extend a subclass of ”arg1” or the class itself

If a class helper inherits from another class helper the extended class must extend either the same class as the parent class helper or a subclass of it

Error: Derived record helper must extend ”arg1”

If a record helper inherits from another record helper it must extend the same record that the parent record helper extended.

Status
Not open for further replies.

  • #1

Program TypeofCreditCard;
Var
AppliName: array[1..99] of String;
SSnum: array[1..99] of Integer;
GSal: array[1..99] of Integer;
TSalD: array[1..99] of Integer;

Name, CC : String;
Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ;

Begin
Writeln ( ‘Enter applicants who applied for a type of credit card’);
Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco… ;

While ( Name <> ‘ Stop ‘ ) do
Begin
NS:= GS-TSD ;
Sum:= Exp + Rep ;
PofIncome:=(NS * 0.45);
Begin
If ( GS >4000) AND ( CC = ‘Bronze Card’ ) then
YS:= GS * 12 ;
C_Amt := YS * 0.25;
i:= i + 1;
AppliName := Name;
SSNum := SSN ;
GSal [ i]:= GS ;
TSalD := TSD ;
End ;
Begin
If (GS >= 7500) AND [CC= ‘Gold Card’] then
YS:= GS * 12 ;
C_Amt:= YS * 0.3;
i:= i + 1 ;
AppliName := Name;
SSnum:=SSN;
GSal:=GS;
TSalD:=TSD;
End;
Begin
If (GS>=10,000) AND ( CC = ‘ Platinum Card’) then
YS := GS * 12;
C_Amt: = YS * 0.4;
i:= i + 1;
A ppliName := Name;
SSNum := SSN;
GSal :=GS;
TSalD := TSD;

End if
End if
End if
End While
End.

The five errors are :
1. Error:Incompatible types: got «Boolean» expected «LongInt» — For this line : If (GS >= 7500) AND [CC= ‘Gold Card’] then

2.Error:Incompatible types: got » Set of Boolean» expected » LongInt» — for the same line (If (GS >= 7500) AND [CC= ‘Gold Card’] then )

3.Error:Incompatible types: got «single» expected «smallint» — for C_Amt := YS * 0.25 ; in Bronze Card

4.Error:Incompatible types: got «extended» expected «smallint» for C_Amt := YS * 0.3; in Gold Card

5.Fatal:syntax error , «)» expected but «,» found — (If GS >= 10000) AND [CC= ‘Platinum’] then )

Thanks for any help. I know my program is by no means perfect because I am awful at Pascal and desperately need help on fixing these things. So I am open to anything that will get this program running in Pascal. Thanks.

Hawkeye22



Feb 10, 2006



713



0



19,460

95


  • #2

1 & 2. Square brackets should be parenthesis:
This: If (GS >= 7500) AND [CC= ‘Gold Card’] then
Should be this: If (GS >= 7500) AND (CC= ‘Gold Card’) then

3 & 4:
You have C_Amt and YS declared as integer yet you are multiplying by a real.

5: there should be no parenthesis at the end of that line.

Your code is hard to read. try indenting where needed. if it was already indented before you copied/pasted, then use the [code ] bbcodes in order to keep the formatting.

Hawkeye22



Feb 10, 2006



713



0



19,460

95


  • #2

1 & 2. Square brackets should be parenthesis:
This: If (GS >= 7500) AND [CC= ‘Gold Card’] then
Should be this: If (GS >= 7500) AND (CC= ‘Gold Card’) then

3 & 4:
You have C_Amt and YS declared as integer yet you are multiplying by a real.

5: there should be no parenthesis at the end of that line.

Your code is hard to read. try indenting where needed. if it was already indented before you copied/pasted, then use the [code ] bbcodes in order to keep the formatting.

Onus



Jan 27, 2006



724



0



19,210

64


  • #3

Well for one thing, the «[» and «]» may not be used in place of parentheses «(» and «)» in boolean expressions to be evaluated. Second, if you want to assign the integer portion of a real number to an integer variable, you need to use a function like TRUNC, as in «integer_var := TRUNC(real_expression);»



Jan 13, 2011



4,165



4



35,260

1,357


  • #4

This is how your program looks when enclosed in [ code ] and [ / code ] tags:

Program TypeofCreditCard; 
Var 
    AppliName: array[1..99] of String; 
    SSnum: array[1..99] of Integer; 
    GSal: array[1..99] of Integer; 
    TSalD: array[1..99] of Integer; 

    Name, CC : String; 
    Rep,Exp, GS,NS,Sum,TSD , YS,SSN,i,C_Amt,PofIncome : integer ; 

Begin 
    Writeln ( 'Enter applicants who applied for a type of credit card'); 
    Readln (Rep,Exp,GS,YS,NS,Sum,TSD,SSN,CC,PofInco... ; 

    While ( Name <> ' Stop ' ) do 
    Begin 
        NS:= GS-TSD ; 
        Sum:= Exp + Rep ; 
        PofIncome:=(NS * 0.45); 
        Begin 
            If ( GS >4000) AND ( CC = 'Bronze Card' ) then 
                YS:= GS * 12 ; 
            C_Amt := YS * 0.25; 
            i:= i + 1; 
            AppliName := Name; 
            SSNum := SSN ; 
            GSal [ i]:= GS ; 
            TSalD := TSD ; 
        End ; 
        Begin 
            If (GS >= 7500) AND [CC= 'Gold Card'] then 
                YS:= GS * 12 ; 
            C_Amt:= YS * 0.3; 
            i:= i + 1 ; 
            AppliName := Name; 
            SSnum:=SSN; 
            GSal:=GS; 
            TSalD:=TSD; 
        End; 
        Begin 
            If (GS>=10,000) AND ( CC = ' Platinum Card') then 
                YS := GS * 12; 
            C_Amt: = YS * 0.4; 
            i:= i + 1; 
            AppliName := Name; 
            SSNum := SSN; 
            GSal :=GS; 
            TSalD := TSD; 
        End if 
        End if 
        End if 
    End While 
End.



Jan 13, 2011



4,165



4



35,260

1,357


  • #5

(sorry for double-post, it will be easier)…

Appart from the errore already discussed, there are some more:
— there are not «end if» and «end while» operators in Pascal (OK, at least in the popular ones);
— your ReadLn statement probably won’t work — string variables will get empty values. Split it on several Write / ReadLn statements
— you have several arrays, but assignment statements are missing [Index] part of the array, e.g. AppliName := Name;
— you are not checking if one will enter more that 100 applicants

  • #6

Thank you everyone. I will give you all an update when i incorporate all of these corrections.

By the way, I am using Free IDE Pascal .

Onus



Jan 27, 2006



724



0



19,210

64


  • #7

I used to use Turbo Pascal. Ah, those were the days…

  • #8

I’m down to 2 errors now and I am pleased but I just really need it to run.
This is the error — Fatal:Syntax Error, «;» expected but «identifier Writeln found — Source of error- Writeln ( ‘Enter applicants who applied for a type of credit card’);

Is there some sort of documentation about what each error means??I want to learn.

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #9

The message means exactly what it says. The compiler was expecting to find «;» but instead it found «Writeln». Normally this means the semicolon is missing from the line before the one listed but your program, as you list it, has no statement before that line. Have you added something since?

  • #10

The message means exactly what it says. The compiler was expecting to find «;» but instead it found «Writeln». Normally this means the semicolon is missing from the line before the one listed but your program, as you list it, has no statement before that line. Have you added something since?

I’ve done nothing but do the changes I’ve been told to made.



Jan 13, 2011



4,165



4



35,260

1,357


  • #11

@Tactical, post your complete code, here or on e.g. PasteBin. If you post it here, encclose it in «code» tags
that is, (omit ‘_’ from example below)
[_code_]
Program something;

end.
[_/code_]

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #13

You have deleted the «Begin» between the variable declarations and the program statements. Reinstate it (just before the offending line) and try again.

  • #14

You have deleted the «Begin» between the variable declarations and the program statements. Reinstate it (just before the offending line) and try again.

I inserted that beginning then one more error came up and it said
Fatal syntax error, «;’ expected but » BEGIN» found



Jan 13, 2011



4,165



4



35,260

1,357


  • #15

@Tactical — it would be helpful if you mention what compiler you’re using, and (when errors happen) — at what line.

On your program:
— Put a «Begin» before first «WriteLn»;
— Put «I := 0» before «while» statement
— change «while» to check that I is less than 100
— change internal «If» to check for «Name <> ‘Stop'»
— Remove last two «End;» before «End.»;

Probably there are more… Change your program, re-post it on PasteBin for further help

  • #16

So i followed through and continued to attempt to run the program and eventually after trying to follow and fix every error , I think it started running but i don’t understand because its been more than 5 hours now that it has said that the PASCAL file is now running but i can not type anything in the black screen and it can not be closed down.Additionally, because I didn’t know it would run after i corrected the last error, this means that I have not saved the most recent version of the PASCAL yet. The problem with that is for my assignment it says » You have to show evidence that your program ran (a print screen after it compiled. Print screen of some data that you entered and a print screen of the output) «

Will it ever run or come off of this screen that it seems to be stuck on?



Jan 13, 2011



4,165



4



35,260

1,357


  • #17

@Tactical — for God’s sake, what version of Pascal are you using?
Try pressing <Ctrl>-<Break>, or <Ctrl>-C, to terminate your program. If you have a debugger in your environment, you can try to terminate your program from there as well.

And since we don’t know how your program looks now, noone can tell what will come out of it ;)

Ijack



Jul 30, 2008



1,035



0



20,360

113


  • #18

The last version of the program that you listed had an infinite loop in it. You never change the value of «Name» inside the «While» loop. This is why the program keeps running.

As the previous poster said, just break into the program. How you do that depends upon your environment.

Status
Not open for further replies.
Thread starter Similar threads Forum Replies Date

B

Solved! Apple Community Reload Error Apps General Discussion 4 Jun 14, 2022

K

Question cache deleted in error Apps General Discussion 1 Apr 25, 2022

xarzu

Question How do I update my computer because I have an error? Apps General Discussion 0 Apr 12, 2022

C

Question Photoshop Elements 2021 error codes 81 and 501 won’t allow installation? How to fix. Apps General Discussion 1 May 5, 2021

aymen9309

Question i need help in a simple pascal program Apps General Discussion 1 Jun 18, 2020

David___Only

Question How to fix“ ERROR-invalid argument/option — ‘Live’ ” in this code? Apps General Discussion 0 Jul 21, 2019

KloneCSGO

Question PUBG Lite launcher error Apps General Discussion 2 Jul 1, 2019

reble

Question Win dos shell syntax error Apps General Discussion 2 Apr 11, 2019

I

Solved! Getting error 502 Bad Gateway, is it proxy or website itself Apps General Discussion 5 Jan 23, 2019

U

ASCII in Pascal programming Apps General Discussion 4 Dec 13, 2015

A

Pascal homework help Apps General Discussion 2 Mar 7, 2015

shiftyape

need help with pascal programming Apps General Discussion 4 Feb 22, 2014

shiftyape

why wont this pascal program work? idk Apps General Discussion 18 Dec 13, 2013

shiftyape

need help with this pascal programming. Apps General Discussion 3 Dec 13, 2013

shiftyape

why doesnt this pascal program work? Apps General Discussion 1 Dec 7, 2013

shiftyape

need help with pascal programming? Apps General Discussion 2 Dec 7, 2013

shiftyape

i need help fixing this pascal program Apps General Discussion 13 Dec 5, 2013

L

Which programming languages will I need to learn as an actuary? Apps General Discussion 2 Dec 12, 2012

M

** A CHALLENGE ** UCSD P-sytem Pascal ** Apps General Discussion 7 Oct 15, 2010

P

pascal quation.. Apps General Discussion 7 Nov 13, 2008

  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions
  • Topics

Понравилась статья? Поделить с друзьями:
  • Error incompatible types got double expected longint
  • Error incompatible types got constant string expected char
  • Error incompatible types got boolean expected real
  • Error incompatible types got boolean expected longint
  • Error incompatible types got boolean expected int64