Compilation failed due to following error s pascal

Даны три слова. Выяснить, является ли хоть одно из них палиндромом Pascal ABC Решение и ответ на вопрос 2941667

0 / 0 / 0

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

Сообщений: 53

1

Даны три слова. Выяснить, является ли хоть одно из них палиндромом

02.02.2022, 14:12. Показов 641. Ответов 5


Даны три слова. Выяснить, является ли хоть одно из них палиндромом («оборотнем»), то есть читаемым одинаково слева направо и справа налево. (Определить функцию, позволяющую распознавать слова-палиндромы.)
Ввод слов с клавиатуры.

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

02.02.2022, 14:12

Ответы с готовыми решениями:

Выяснить, является ли хоть одно из двух заданных чисел палиндромом
Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом ("перевертышем"),…

Даны 2 натуральных числа выяснить является ли хоть одно из них палиндромом (перевёртышем)
Даны 2 натуральных числа выяснить является ли хоть одно из них палиндромом(перевёртышем) тоесть…

Выяснить, является ли хоть одно из чисел палиндромом
Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом («перевертышем»),…

Даны три слова. Определить, является ли хоть одно из них палиндромом
Даны три слова. Определить, является ли хоть одно из них палиндромом ("перевёртышем"), т.е таким,…

5

thyrex

Вирусоборец

11103 / 6337 / 1312

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

Сообщений: 24,072

02.02.2022, 15:23

2

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
const yes = 'является палиндромом'; 
 
 function isPalindrom(s0: string): boolean;
 var s: string;
      i: integer;
 begin
  s:= '';
  for i:= length(s0) downto 1 do
   s:= s + s0[i];
  result:= s = s0;
 end;
 
begin
 write('s1 = ');
 readln(s1);
 if isPalindrom(s1)
  then writeln(yes)
  else writeln('не ' + yes);
 write('s2 = ');
 readln(s2);
 if isPalindrom(s2)
  then writeln(yes)
  else writeln('не ' + yes);
 write('s3 = ');
 readln(s3);
 if isPalindrom(s3)
  then writeln(yes)
  else writeln('не ' + yes);
end.



0



bormant

Модератор

Эксперт Pascal/DelphiЭксперт NIX

7502 / 4370 / 2776

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

Сообщений: 12,506

Записей в блоге: 1

02.02.2022, 15:35

3

Лучший ответ Сообщение было отмечено DenGI235 как решение

Решение

Другой вариант без копирования строки:

Pascal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function IsPalindrom(const s: String): Boolean;
var i, j: Integer;
begin
  i:=1; j:=Length(s);
  while (i<j) and (s[i]=s[j]) do begin
    Inc(i); Dec(j);
  end;
  IsPalindrom:=i>=j;
end;
var
  i: Integer;
  s: String;
begin
  for i:=1 to 3 do begin
    Write('s',i,': '); ReadLn(s);
    if not IsPalindrom(s) then Write('НЕ '); WriteLn('палиндром');
  end;
end.

Добавлено через 2 минуты
Хотя, по условию нужен несколько иной ответ:

Цитата
Сообщение от DenGI235
Посмотреть сообщение

является ли хоть одно из них палиндромом

Pascal
10
11
12
13
14
15
16
17
18
19
var
  i, k: Integer;
  s: String;
begin {k:=0;}
  for i:=1 to 3 do begin
    Write('s',i,': '); ReadLn(s);
    if IsPalindrom(s) then Inc(k);
  end;
  WriteLn(k>0);
end.

Добавлено через 1 минуту
Другой вариант:

Pascal
10
11
12
13
14
15
16
17
18
19
20
var
  i: Integer;
  s: String;
  b: Boolean;
begin {k:=0;}
  for i:=1 to 3 do begin
    Write('s',i,': '); ReadLn(s);
    b:=b or IsPalindrom(s);
  end;
  WriteLn(b);
end.



0



0 / 0 / 0

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

Сообщений: 53

02.02.2022, 15:37

 [ТС]

4

Compilation failed due to following error(s).
Выдает ошибку (первый вариант) , щас попробую еще варианты



0



thyrex

Вирусоборец

11103 / 6337 / 1312

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

Сообщений: 24,072

02.02.2022, 15:48

5

Цитата
Сообщение от bormant
Посмотреть сообщение

Другой вариант без копирования строки:

или так

Pascal
1
2
3
4
5
6
7
8
9
function IsPalindrom(const s: string): boolean;
var i, j: Integer;
begin
 i:=1;
 j:=Length(s);
 while (i<=j div 2) and (s[i]=s[j-i+1]) do
   inc(i);
 Result:= i>j div 2;
end;

Добавлено через 54 секунды

Цитата
Сообщение от DenGI235
Посмотреть сообщение

Compilation failed due to following error(s).

я там забыл переменные объявить



0



Модератор

Эксперт Pascal/DelphiЭксперт NIX

7502 / 4370 / 2776

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

Сообщений: 12,506

Записей в блоге: 1

02.02.2022, 15:55

6

Цитата
Сообщение от thyrex
Посмотреть сообщение

или так

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



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

02.02.2022, 15:55

Помогаю со студенческими работами здесь

Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом
Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом («перевертышем»),…

Выяснить, является ли хоть одно из заданных чисел палиндромом
Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом, т.е. таким числом,…

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

Выяснить, является ли хоть одно из трех слов палиндромом
32. Даны три слова. Выяснить, является ли хоть одно из них палиндромом («перевертышем»), т. е….

Выяснить является ли хоть одно из данных чисел палиндромом(перевёртышем)
Даны 2 натуральных числа выяснить является ли хоть одно из них палиндромом(перевёртышем) тоесть…

Выяснить, является ли хоть одно из заданных слов палиндромом (GUI-приложение)
Даны три слова. Выяснить, является ли хоть одно из них палиндромом (&quot;перевертышем&quot;), т. е. таким,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

6

I have the following program that compiles successfully on my machine using GCC 7.5.0 but when i try out the program here the program doesn’t work.

class Foo 
{
    friend void ::error() { }

};
int main()
{
    
    return 0;
}

The error here says:

Compilation failed due to following error(s).

    3 |     friend void ::error() { }
      |                         ^

My question what is the problem here and how can i solve it.

asked Feb 6, 2022 at 7:25

Jason Liam's user avatar

Jason LiamJason Liam

32.4k5 gold badges21 silver badges52 bronze badges

3

The problem is that a qualified friend declaration cannot be a definition. In your example, since the name error is qualified(because it has ::) so the corresponding friend declaration cannot be a definition.

This seems to be a bug in GCC 7.5.0. For example, for gcc 7.5.0 the program works but for gcc 8.4.0 and higher it doesn’t work.

One way to solve thiswould be to remove the body { } of the error function and make it a declaration by adding semicolon ; as shown below:

//forward declare function error()
void error();

class Foo 
{
    friend void ::error();//removed the body { } . This is now a declaration and not a definition

};
int main()
{
    
    return 0;
}
//definition of function error 
void error()
{
    
}

Note you can also put the definition of function error() before the definition of class Foo as shown here.

Another way to solve this would be to remove the :: and make error an unqualified name as shown here

answered Feb 6, 2022 at 7:34

Jason Liam's user avatar

Jason LiamJason Liam

32.4k5 gold badges21 silver badges52 bronze badges

error messages

Contents

Errors during compilation

Unless the error identifies itself as an internal compiler error, it is unlikely that the error is caused by a bug in the compiler or its runtime library. Syntax errors are almost always due to incorrect code. Refer to the FPC Parser Messages documentation for a listing of the various Error and Warning messages produced by the FPC Parser along with explanations of them.

If you encounter an error while compiling your code and are unable to resolve it yourself, please use the FPC and Lazarus Forums, write to the Lazarus or Free Pascal mailing list or join the #fpc or #lazarus-ide IRC channel. The problem may then be solved more quickly.

If an error is encountered during compilation, the compiler does not generate an executable program. See further compile time errors.

Errors during program execution

The Free Pascal Compiler inserts code to detect a large number of error situations which might occur during program execution (eg divide by zero). If such an error situation occurs, the standard run-time library will terminate the program and print a runtime error number and the address at which the error occurred. See further runtime errors.

If you encounter a runtime error while running your program and are unable to resolve it yourself, please use the FPC and Lazarus Forums, write to the Lazarus or Free Pascal mailing list or join the #fpc or #lazarus-ide IRC channel.

If the bug is already known

Use the FPC and Lazarus Bug Tracker’s search capabilities.

Known issues. Tip: If you are experiencing problems, for example with TEdit.SelStart -> try searching «SelStart» (in quotes). If the bug is known:

  • reopen if the issue is resolved or the issue is closed — use the Reopen Issue button.
  • add your own note to the discussion if you received this error in another situation.

To observe any changes to your bug report — use the Monitor Issue button.

Note: You need to login to your account: Login/Create an account.

If the bug is not already known

  1. Go to the FPC and Lazarus Bug Tracker.
  2. You must be logged in: Login/Create account.
  3. Visit Report Issue. Fill in as many fields as possible. The more accurate the better.
  • The OS and Product Version fields are especially important. If the data is not enough, they will not help you! Don’t forget to mention the system features (big endian or 64-bit).
  • It is often helpful to send in a small test program to resolve the problem as soon as possible.
  • If you find graphic artifacts, it would not be superfluous to send a screenshot (in png or jpeg, but not in BMP!).
  • If it fails, try creating a backtrace. More information — Creating a Backtrace with GDB.
  • If possible, observe the behaviour of the buggy program on different platforms or with different widgetsets.

It is also possible to get a bug fixed by paying for a solution, see Bounties.

Источник

Ошибки компиляции

Основные ошибки

IO-error -2 at

В ОС LINUX вы можете получить это сообщение при старте компилятора. Обычно оно означает, что компилятор не нашёл файл определений ошибок. Вы можете исправить это недоразумение с помощью параметра -Fr (см. раздел 5.1.3) для LINUX.

Error : File not found : xxx or Error: couldn’t compile unit xxx

Это сообщение обычно появляется, когда путь к вашему модулю неправильно установлен. Помните, что компилятор ищет модули только в текущей директории и в директории, где находится сам компилятор. Если вы хотите, чтобы поиск выполнялся также в других местах, то вы должны явно указать эти места компилятору с помощью параметра -Fu (см. раздел 5.1.3). Или потребуется настроить конфигурационный файл.

Ошибки, которые могут встретиться в DOS

No space in environment

Эта ошибка может появиться, если вы вызываете файл SET_PP.BAT из AUTOEXEC.BAT. Для решения этой проблемы вы должны увеличить расширенную память для среды окружения. Чтобы это сделать, найдите в файле CONFIG.SYS строку, подобную этой: и измените её следующим образом Если этот параметр уже установлен, то вы можете только увеличить это значение.

Coprocessor missing

Если компилятор выдаёт сообщение об отсутствии сопроцессора, установите режим эмуляции сопроцессора.

Not enough DPMI memory

Если вы хотите использовать компилятор с DPMI, вы должны иметь не менее 7-8 MB свободной памяти DPMI, но 16 Mb являются более предпочтительным объёмом.

Источник

Free pascal compilation error

NGX » 10.04.2010 20:51:32

Re: Fatal:Compilation aborted.

Vadim » 11.04.2010 04:32:22

Re: Fatal:Compilation aborted.

NGX » 11.04.2010 16:30:13

First compilation of c:documents and settingsngxРабочий стол1f.pas
Fatal: Compilation aborted

Recompiling because of E:. pascalggggg1.pas
Fatal: Compilation aborted

Re: Fatal:Compilation aborted.

Vadim » 11.04.2010 16:52:21

Re: Fatal:Compilation aborted.

NGX » 11.04.2010 17:00:42

Re: Fatal:Compilation aborted.

serg_iv » 11.04.2010 17:47:27

Re: Fatal:Compilation aborted.

Sergei I. Gorelkin » 11.04.2010 18:21:16

Re: Fatal:Compilation aborted.

NGX » 11.04.2010 18:33:52

Re: Fatal:Compilation aborted.

Padre_Mortius » 11.04.2010 21:41:06

Re: Fatal:Compilation aborted.

NGX » 11.04.2010 23:06:18

Re: Fatal:Compilation aborted.

Максим » 12.04.2010 00:47:40

Видимо, вы столкнулись с этой ошибкой.

Re: Fatal:Compilation aborted.

NGX » 14.04.2010 21:29:02

Re: Fatal:Compilation aborted.

Максим » 15.04.2010 00:33:58

А что не получается-то?

Её надо распаковать, записать в каталог bini386-win32 файл fpc.cfg (можно взять от стабильной версии, исправив в нём пути), прописать к ней путь в переменной PATH.

Re: Fatal:Compilation aborted.

informat » 28.10.2010 06:44:25

Максим писал(а): Видимо, вы столкнулись с этой ошибкой.

Кажется там забыли про файл cygwin1.dll

Re: Fatal:Compilation aborted.

vada » 07.09.2011 13:41:13

Таже фигня. Если «Собрать» или «Запустить» получаю ошибку. Если «Собрать все» потом «Запустить» ошибки не получаю.

Free Pascal Compiler version 2.4.2 [2011/03/08] for i386
Copyright (c) 1993-2010 by Florian Klaempfl
d:Lazarusfpc2.4.2bini386-win32ppc386.exe

Источник

Free pascal compilation error

Applications generated by Free Pascal might generate run-time errors when certain abnormal conditions are detected in the application. This appendix lists the possible run-time errors and gives information on why they might be produced. 1 Invalid function number An invalid operating system call was attempted. 2 File not found Reported when trying to erase, rename or open a non-existent file. 3 Path not found Reported by the directory handling routines when a path does not exist or is invalid. Also reported when trying to access a non-existent file. 4 Too many open files The maximum number of files currently opened by your process has been reached. Certain operating systems limit the number of files which can be opened concurrently, and this error can occur when this limit has been reached. 5 File access denied Permission to access the file is denied. This error might be caused by one of several reasons:

  • Trying to open for writing a file which is read-only, or which is actually a directory.
  • File is currently locked or used by another process.
  • Trying to create a new file, or directory while a file or directory of the same name already exists.
  • Trying to read from a file which was opened in write-only mode.
  • Trying to write from a file which was opened in read-only mode.
  • Trying to remove a directory or file while it is not possible.
  • No permission to access the file or directory.

6 Invalid file handle If this happens, the file variable you are using is trashed; it indicates that your memory is corrupted. 12 Invalid file access code Reported when a reset or rewrite is called with an invalid FileMode value. 15 Invalid drive number The number given to the Getdir or ChDir function specifies a non-existent disk. 16 Cannot remove current directory Reported when trying to remove the currently active directory. 17 Cannot rename across drives You cannot rename a file such that it would end up on another disk or partition. 100 Disk read error An error occurred when reading from disk. Typically happens when you try to read past the end of a file. 101 Disk write error Reported when the disk is full, and you’re trying to write to it. 102 File not assigned This is reported by Reset , Rewrite , Append , Rename and Erase , if you call them with an unassigned file as a parameter. 103 File not open Reported by the following functions : Close, Read, Write, Seek, EOf, FilePos, FileSize, Flush, BlockRead, and BlockWrite if the file is not open. 104 File not open for input Reported by Read, BlockRead, Eof, Eoln, SeekEof or SeekEoln if the file is not opened with Reset . 105 File not open for output Reported by write if a text file isn’t opened with Rewrite . 106 Invalid numeric format Reported when a non-numeric value is read from a text file, and a numeric value was expected. 107 Invalid enumeration Reported when a text representation of an enumerated constant cannot be created in a call to str or write(ln). 150 Disk is write-protected (Critical error) 151 Bad drive request struct length (Critical error) 152 Drive not ready (Critical error) 154 CRC error in data (Critical error) 156 Disk seek error (Critical error) 157 Unknown media type (Critical error) 158 Sector Not Found (Critical error) 159 Printer out of paper (Critical error) 160 Device write fault (Critical error) 161 Device read fault (Critical error) 162 Hardware failure (Critical error) 200 Division by zero The application attempted to divide a number by zero. 201 Range check error If you compiled your program with range checking on, then you can get this error in the following cases: 1. An array was accessed with an index outside its declared range. 2. Trying to assign a value to a variable outside its range (for instance an enumerated type). 202 Stack overflow error The stack has grown beyond its maximum size (in which case the size of local variables should be reduced to avoid this error), or the stack has become corrupt. This error is only reported when stack checking is enabled. 203 Heap overflow error The heap has grown beyond its boundaries. This is caused when trying to allocate memory explicitly with New , GetMem or ReallocMem , or when a class or object instance is created and no memory is left. Please note that, by default, Free Pascal provides a growing heap, i.e. the heap will try to allocate more memory if needed. However, if the heap has reached the maximum size allowed by the operating system or hardware, then you will get this error. 204 Invalid pointer operation You will get this in several cases:

  • if you call Dispose or Freemem with an invalid pointer
  • in case New or GetMem is called, and there is no more memory available. The behavior in this case depends on the setting of ReturnNilIfGrowHeapFails . If it is True , then Nil is returned. if False , then runerror 204 is raised.

205 Floating point overflow You are trying to use or produce real numbers that are too large. 206 Floating point underflow You are trying to use or produce real numbers that are too small. 207 Invalid floating point operation Can occur if you try to calculate the square root or logarithm of a negative number. 210 Object not initialized When compiled with range checking on, a program will report this error if you call a virtual method without having called its object’s constructor. 211 Call to abstract method Your program tried to execute an abstract virtual method. Abstract methods should be overridden, and the overriding method should be called. 212 Stream registration error This occurs when an invalid type is registered in the objects unit. 213 Collection index out of range You are trying to access a collection item with an invalid index ( objects unit). 214 Collection overflow error The collection has reached its maximal size, and you are trying to add another element ( objects unit). 215 Arithmetic overflow error This error is reported when the result of an arithmetic operation is outside of its supported range. Contrary to Turbo Pascal, this error is only reported for 32-bit or 64-bit arithmetic overflows. This is due to the fact that everything is converted to 32-bit or 64-bit before doing the actual arithmetic operation. 216 General Protection fault The application tried to access invalid memory space. This can be caused by several problems: 1. Dereferencing a nil pointer. 2. Trying to access memory which is out of bounds (for example, calling move with an invalid length). 217 Unhandled exception occurred An exception occurred, and there was no exception handler present. The sysutils unit installs a default exception handler which catches all exceptions and exits gracefully. 218 Invalid value specified Error 218 occurs when an invalid value was specified to a system call, for instance when specifying a negative value to a seek() call. 219 Invalid typecast

Thrown when an invalid typecast is attempted on a class using the as operator. This error is also thrown when an object or class is typecast to an invalid class or object and a virtual method of that class or object is called. This last error is only detected if the -CR compiler option is used. 222 Variant dispatch error No dispatch method to call from variant. 223 Variant array create The variant array creation failed. Usually when there is not enough memory. 224 Variant is not an array This error occurs when a variant array operation is attempted on a variant which is not an array. 225 Var Array Bounds check error This error occurs when a variant array index is out of bounds. 227 Assertion failed error An assertion failed, and no AssertErrorProc procedural variable was installed. 229 Safecall error check This error occurs is a safecall check fails, and no handler routine is available. 231 Exception stack corrupted This error occurs when the exception object is retrieved and none is available. 232 Threads not supported Thread management relies on a separate driver on some operating systems (notably, Unixes). The unit with this driver needs to be specified on the uses clause of the program, preferably as the first unit ( cthreads on unix).

Источник

Mac Installation FAQ

This article applies to macOS only.

This page lists solutions to the most frequent problems that may arise during (and after) installation of Lazarus and Free Pascal on macOS. Please read Installing Lazarus on macOS first and pay special attention to the sections that apply to your versions of macOS, Xcode, Lazarus and Free Pascal.

Contents

Lazarus doesn’t run project

After moving to macOS or after upgrading to a new version of macOS Lazarus is unable to compile and run a project.

Solution: Most likely, this behaviour results from missing command line tools. In newer versions of Xcode they are no longer installed by default. You can install them by running

from the terminal. See also Installing Lazarus on macOS for more details.

Compilation aborts with weird messages

I have correctly installed Lazarus and FPC, but compiling a simple demo program stops with the Free Pascal exit code 256 and the message «Lazarus Panic /bin/sh: clang: command not found».

Solution: This behaviour may arise from a too old Xcode version installed. Generally, you should use the newest Xcode version that is available for your operating system. Lazarus 1.6 requires, e.g., Xcode 3.2.6, or newer. With Xcode 4.3 or newer, you should also install the Xcode command line tools as described above or in the article Installing Lazarus on macOS.

ld: symbol(s) not found for architecture i386

I am trying to compile a blank project on Catalina immediately after installing FPC and Lazarus but I get this error «ld: symbol(s) not found for architecture i386».

Solution: Go to Lazarus > Tools > Options, if your compiler is set to ppc386 (32 bit), then change it to ppcx64 (64 bit) or fpc (a wrapper that should choose the correct compiler). There is no 32 bit support in Catalina. In later versions of Lazarus, the Lazarus > Tools > Options menu has been moved to the Lazarus > Preferences menu

Debugger not found

I have installed the latest version of Lazarus on a new Mac. My program is built fine, but when I try to run it I get a message that the debugger /usr/bin/gdb doesn’t exist or isn’t runnable.

Solution: Since version 5, Xcode does not include the GDB debugger but the LLDB debugger. For recent versions of macOS, go to the Tools > Options | Debugger menu and choose «LLDB debugger (with fpDebug) (Beta)» and set the executable to /usr/bin/lldb. In later versions of Lazarus, the Tools > Options menu has been moved to the Lazarus > Preferences menu

Solution (legacy): Xcode v5 no longer includes the GDB debugger. See GDB on OS X Mavericks or newer and Xcode 5 or newer for possible solutions unless you are running a recent version of macOS (in which case, see above).

Form not shown after moving to Mac

My application works well on Windows and Linux, but after changing to Mac my forms are invisible. I tried to re-scan the FPC source directory, and I clicked «Create Bundle», but this didn’t solve the problem. Unlike my app, a very simple demo application works well.

Solution: This may result from a wrong position setting of your form(s). Your Windows machine may have a multi-monitor setup, so that the forms are outside the visible area of a single-monitor environment, i.e. if your Mac has only one monitor. You should check and correct the top and left properties of your forms in the object inspector. (Of course, this also applies in the other direction, i.e. if you have a multi-monitor Mac and a single-monitor Windows or Linux machine).

Form not responding to mouse clicks

After starting the program the form is visible, but not responding to interaction via the user interface.

Solution: Programs for macOS-based systems are more complex than programs for Windows or Linux. They require the existence of an application bundle, a special opaque directory structure, which determines the modalities of interaction with the operating system and the GUI. You may create an application bundle in the project settings or alternatively via shell commands. Make sure that the option Use Application Bundle for running and debugging (for Darwin) is checked.

fpcsrc not present

After installing and first running Lazarus, the welcome window complains that the directory «/usr/local/share/fpcsrc» is not found.

Solution: You have to install fpcsrc. This is a Lazarus-specific installer package that comes with your distribution of Lazarus. If you have downloaded Lazarus from SourceForge you find fpcsrc in the same server directory as the Lazarus package.

Multiple error messages after upgrading Lazarus and/or FPC

After upgrading Lazarus and/or Free Pascal to a new major version, trying to compile my code results in multiple error messages.

Solution: This behaviour may have multiple reasons. After every major upgrade you should rescan the FPC source directory. If this doesn’t help it may be useful to delete the file fpcdefines.xml (it is within the

/.lazarus folder). Additionally, you should check your code for incompatibilities that may result from changes in the compiler (although this is quite rare with code that is not too unusual). See Category:FPC User Changes by release for intentional changes to the compiler that may break existing code.

Unit XY not found

I have freshly installed a new version of Lazarus on my machine. Trying to compile an application results in the error message «Error: unit not found: XY». (XY is a place holder for any unit name.)

Solution: Try to re-scan your FPC source directory via the Lazarus IDE Tools. menu.

Fatal: Cannot find [. ] used by [. ], incompatible ppu=[filename], package [package name]

When the compiler gives the message «Cannot find A used by B», Lazarus checks what pas/pp/ppu files are in the search path, and if there is a ppu file it inserts «incompatible ppu=filename, package».

Explanation: FPC cannot use this ppu for one of these reasons:

  • it was compiled with another FPC version;
  • it was compiled with (depends on) some other ppu files that are not in the search path;
  • you misconfigured some search path(s).

Solutions: (1) Check that you have the current Xcode (optional — see here) and Xcode command line tools package (mandatory) installed; (2) Lazarus > Menu > Tools > Configure Build Lazarus — Find and check «Clean all» and then Build. If that doesn’t work, I’d be tempted to delete both FPC + Lazarus and start again. See Uninstalling Lazarus and Free Pascal.

Error: User defined: only cpu i386 is supported

When compiling Lazarus on macOS I receive this error: carbonbars.pp(16,2) Error: User defined: only cpu i386 is supported

Error: ld: framework not found Cocoa

When compiling Lazarus on macOS I receive this error: Error: ld: framework not found Cocoa

Solution: You forgot to install the Xcode command line tools or they’ve since been deleted. See Installing Xcode Command Line Tools to resolve. You may also need to either:

(1) re-install FPC after installing the Xcode command line tools; or

(2) tweak the /private/etc/fpc.cfg file, after installing the Xcode command line tools, by adding:

so that the compiler can find the macOS frameworks.

Error ppc1 not found

When compiling the Free Pascal Compiler on macOS I receive this error:

Solution: GNU Make does not handle directory names with spaces in them. Rename «fpc trunk» to «fpc_trunk» or similar and it should work without this error.

Error: library (X11 or Truetype) not found

If you are compiling X11 applications (typically using fpGui) FPC needs to know where to find the libX11.dylib and libfreetype.dylib libraries. If FPC cannot find these libraries, you will receive a library not found error during linking.

Solution: Depending on your version of macOS or XQuartz these may be found in /usr/X11/lib or /opt/X11/lib with a symlink from /usr. The best solution to this is probably to edit /etc/fpc.cfg and add the line -Fu/usr/X11/lib

Application does not accept keyboard input

After compiling my application, I cannot enter anything in the edit boxes and the application will not accept any keyboard input.

Solution: You forgot to create an application bundle. Lazarus > Project > Project Options > Application — Create Application Bundle.

Warning arm64 function not 4-byte aligned

When compiling on an Apple Silicon M1 processor, I get a «warning arm64 function not 4-byte aligned» for every function.

Solution: That’s probably a consequence of using -Os. That setting unconditionally sets procalign (jump align) to 1. That’s definitely wrong for AArch64 and a bunch of other architectures. There is no «minimum required alignment» for these settings defined yet anywhere in the compiler, so that will need to be added. In the meantime, do not use -Os to optimize size.

Resource compiler «fpcres» not found

When compiling an application after installing or compiling a new Lazarus version, it fails with the error «Error (9021) Resource compiler «fpcres» not found, switching to external mode«

Solution: Create a file called .fpc.cfg (note the leading dot in the filename) in your home directory and add the lines:

If the file already exists it should contain the first of the lines above, so just add the second line.

ld: file not found: /usr/lib/crt1.10.5.o

When compiling FPC from source, linking fails with «ld: file not found: /usr/lib/crt1.10.5.o»

Solution: Add «OPT=»-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk» to your make command line — the reason is that when compiling the FPC source, the fpc.cfg file, which contains this option, is not used.

ld: library not found for -lc

When compiling FPC from source, I get this «ld: library not found for -lc, An error occurred while linking «

Explanation: The compiler cannot find the operating system SDK frameworks.

  • If you have not installed the command line tools, you need to do so. Note that when you upgrade the operating system, the command line tools are deleted during the upgrade process.
  • If you have installed the command line tools, then you need to tell the compiler where to find the SDK frameworks by adding:

OPT=»-XR/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/» to your make command line. Note that older versions of the command line tools (eg those for Mountain Lion 10.8.5) did not also install the SDK frameworks in which case you will need to install the latest version of the full Xcode package for your operating system and, for example, adding: OPT=»-XR/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/» to your make command line.

codesign error when compiling FPC from source

When compiling FPC on older versions of macOS, I receive this error:

Explanation: Older versions of the macOS codesign command line utility do not have a —remove-signature option.

Solution: You can provide a custom codesign command via the CODESIGN=xxx make parameter to your make command line. You could use CODESIGN=/usr/bin/true to work around it.

Error: Internal error 200609171

When compiling my Objective-Pascal delegate function(s)/procdeure(s) the compiler stops with this error: «Error: Internal error 200609171».

Explanation: The internal error comes from using the DWARFv3 (-gw3) information format for debugging. There is a bug in the Free Pascal Compiler up to and including 3.2.2 related to generating debug information for Objective-Pascal with that format.

Solution: Switch to using the DWARFv2 (-gw) debugging information format OR use FPC main (development version 3.3.1).

Lazarus reports success, but there are errors!

I compiled my application and although Lazarus says my application compiled successfully, there are a bunch of errors shown. For example —

Explanation: These are actually harmless warnings from the assembler, but for some reason Lazarus shows them as errors. Just ignore them.

GUI application menu inaccessible

My GUI application menu is not accessible

Solution: All macOS GUI applications must be wrapped in an Application Bundle.

Other questions

I didn’t find my issue here.

Solution: You might find a possible solution at the Lazarus and Free Pascal Forum. Otherwise, you might ask your question there.

Источник

Содержание

  1. Compilation failed due to following error перевод
  2. «503 Service Temporarily Unavailable»: перевод, что значит и как исправить
  3. Причины появления
  4. Как исправить ошибку
  5. Как действовать вебмастеру
  6. Undefined reference to main c++ [SOLVED]
  7. undefined reference to ‘main’ c++
  8. SOLUTION : Undefined reference to main c++
  9. undefined reference to func() c++
  10. SOLUTION : Undefined reference to function c++
  11. Reader Interactions
  12. Leave a Reply Cancel reply
  13. Primary Sidebar
  14. Search here
  15. Social Media
  16. SEE MORE
  17. Fibonacci sequence c++
  18. C++ Map [Learn by Example]
  19. how to copy paste in turbo c++ ?
  20. return 0 c++
  21. c++ expected a declaration [ SOLVED]

Compilation failed due to following error перевод

I got below errors while run the code. any ideawhat are these errors?
I use c++14.

Below are the errors:

Compilation failed due to following error(s).In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq ::__single_object std::make_unique(_Args&& . ) [with _Tp = Rectangle; _Args = ; typename std::_MakeUniq ::__single_object = std::unique_ptr >]’:
main.cpp:60:74 : required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Rectangle’
< return unique_ptr (new _Tp(std::forward (__args). )); >
^

main.cpp:24:7: note: because the following virtual functions are pure within ‘Rectangle’:
class Rectangle: public Shape
^

main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^

In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq ::__single_object std::make_unique(_Args&& . ) [with _Tp = Triangle; _Args = ; typename std::_MakeUniq ::__single_object = std::unique_ptr main.cpp:61:73 : required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Triangle’
< return unique_ptr (new _Tp(std::forward (__args). )); >
^

main.cpp:33:7: note: because the following virtual functions are pure within ‘Triangle’:
class Triangle: public Shape
^

main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^

In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq ::__single_object std::make_unique(_Args&& . ) [with _Tp = Circle; _Args = ; typename std::_MakeUniq ::__single_object = std::unique_ptr >]’:
main.cpp:62:60 : required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Circle’
< return unique_ptr (new _Tp(std::forward (__args). )); >
^

main.cpp:42:7: note: because the following virtual functions are pure within ‘Circle’:
class Circle : public Shape
^

main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^

Note you should be getting several warnings that give you valuable hints as to what is wrong, never ignore warnings.

The first thing I would recommend is that you comment out the code in main after your «cin» statement and just create one instance of one of your classes. For example «Rectangle test(rectHeight, rectWidth);» , get that one line to compile correctly before you try to complicate things with the vector and the unique_ptr.

With just that one instance here are the messages I get:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
/main.cpp|10|warning: ‘class Shape’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|24|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|24|warning: ‘class Rectangle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|33|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|33|warning: ‘class Triangle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|42|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|42|warning: ‘class Circle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp||In function ‘int main()’:|
/main.cpp|58|error: no matching function for call to ‘Rectangle::Rectangle(int&, int&)’|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle()’|
/main.cpp|24|note: candidate expects 0 arguments, 2 provided|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle(const Rectangle&)’|
/main.cpp|24|note: candidate expects 1 argument, 2 provided|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle(Rectangle&&)’|
/main.cpp|24|note: candidate expects 1 argument, 2 provided|
/main.cpp|58|error: cannot declare variable ‘test’ to be of abstract type ‘Rectangle’|
/main.cpp|24|note: because the following virtual functions are pure within ‘Rectangle’:|
/main.cpp|21|note: ‘virtual double Shape::getarea() const’|
||=== Build failed: 2 error(s), 7 warning(s) (0 minute(s), 1 second(s)) ===|

Fixing those warnings is very important. You also seem to need several constructor and destructors.

If I comment below lines, I can see the below error. Can you provide some inputs here?

//std::vector > shapes;
//shapes.emplace_back(std::make_unique (rectHeight, rectWidth));
//shapes.emplace_back(std::make_unique (triaHeight, triaWidth));
//shapes.emplace_back(std::make_unique (circRadius));

Below is the error.

main.cpp: In function ‘int main()’:
main.cpp:66:43: error: ‘shapes’ was not declared in this scope
const int totalArea = std::accumulate(shapes.begin(), shapes.end(), 0, [](int total, const auto& shape)

Minor: Lines 6-7 are unnecessary if you’re going to bring in the entire std namespace at line 8. Suggestion: Change line 8 to using std::string;

Line 21 is a pure virtual function making Shape an abstract class. The compiler is telling you you can’t instantiate a Rectangle because Shape is an abstract class. This is because there is no overload in Rectangle because there is no overload for line 21. Note that line 27 does not overload line 21 because of a difference in constness of the two functions.

Line 60: You’re trying to construct a Rectangle with 2 arguments. Rectangle has no such constructor.

Line 68: totalArea is an int . getArea() return a double .

I have made the below changes, please check the code. I am not sure why again those errors are seen here? please help me.

Источник

«503 Service Temporarily Unavailable»: перевод, что значит и как исправить

Всем привет! Сегодня мы рассмотрим «Ошибку 503». «Error 503 Service Temporarily Unavailable» (перевод с англ. языка – «Служба Временно Недоступна») – критическая ошибка, появляющаяся при подключении к веб-серверу, неспособному в текущий момент обработать входящий запрос по техническим причинам – из-за перерыва на обслуживание и вынужденных обновлений, инициированных вебмастером.

Несмотря на наличие точной кодировки, а порой еще и с дополнительным описанием, расшифровать выдаваемое сообщение, и сразу принять меры – сложно. Виной тому – разное наименование в зависимости от конфигурации веб-сервера, выбранной системы управления содержимым: WordPress, Joomla, DLE и т.д. В результате «Error 530» часто превращается и в «HTTP 503», и в «Http/1.1 error 503 Service Unavailable». Отсюда и появляются дополнительные сложности, вынуждающие заняться углубленной диагностикой.

«The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.»

ПЕРЕВОД: Сервер временно не может обслуживать ваш запрос из-за простоя технического обслуживания или проблем с емкостью. Пожалуйста, повторите попытку позже.

Причины появления

  • Запрашиваемая веб-страница потеряла связь с базой данных из-за повышенного спроса и сильной нагрузки на сервер. Проблема временная и часто решается даже без личного вмешательства.
  • Установленные плагины, расширения или компоненты на сайте несовместимы, давно не обновлялись или загружены не из официальных источников для каждой CMS (системы управления содержимым), а со сторонних сайтов, а потому небезопасны и приводят к ошибкам. Если дополнительные инструменты уже добавлены, то отключать лишние элементы придется уже на хостинге, а не через «Панель администратора».
  • Добавленные на Web-страницу скрипты долго обрабатываются, из-за чего сайт сбрасывает текущее соединение с пользователем.
  • «503 ошибка» – часто свидетельствует о слабой пропускной способности и низкой мощности выбранного хостинга (преимущественно бесплатного). Из-за неожиданного наплыва новых пользователей, сайт банально не справляется с нагрузкой.

Как исправить ошибку

Со стороны клиента, обращающегося к веб-ресурсу с «ошибкой 503», повлиять на ситуацию невозможно – технические неполадки связаны напрямую с сервером принимающей стороны. И восстанавливать работоспособность сайта предстоит уже администраторам или разработчикам.

Пользователям остается или периодически обновлять страницу, или проверять наличие ошибок сторонними инструментами, вроде диагностического сервиса «IsItDownRightNow». Стоит добавить ссылку в текстовое поле, нажать на кнопку «Check» и на экране появится результат – сайт недоступен, доступ ограничен или веб-страницы загружаются в штатном режиме.

Если сервис IsItDownRightNow подтвердил работоспособность, но ошибка 503 никуда не исчезла, придется экспериментировать. Начать лучше с перезагрузки роутера или маршрутизатора, а после – выбрать сторонний браузер. Вместо Google Chrome – Mozilla Firefox или Microsoft Edge.

Как действовать вебмастеру

Администраторы и разработчики повлиять на ситуацию способны в полной мере, главное – знать какие вещи исправлять и к чему стремиться:

  • Желательно отказаться от тяжелых и ресурсоемких скриптов, при загрузке часто обращающихся к базе данных. Как показывает практика – перенасыщение скриптами происходит при использовании шаблонов для CMS. Стоит просмотреть информацию о содержимом шаблонов и сразу отказаться от лишних элементов. Оставить рекомендуется: инструменты кэширования и оптимизации страниц, сервисы сжатия изображений, и подготовки бэкапов по расписанию.
  • При использовании ежедневной информационно-развлекательной почтовой рассылки рекомендуется сменить время для передачи сообщений с часа-пик, когда посетителей на сайте необычайно много, на ранее утро или позднюю ночь. Так сайту не придется обрабатывать случайные запросы пользователей, а затем еще и упаковывать корреспонденцию.
  • О регулярных обновлениях CMS, плагинов или расширений стоит вспоминать хотя бы 2-3 раза в неделю. А вот соглашаться на фоновые апдейты в автоматическом режиме не стоит – могут возникнуть уже новые проблемы с несовместимостью или ненужными нововведениями.
  • Для изображений, публикуемых на сайте, лучше загрузить дополнение, способное сжимать контент до определенного размера или в каком-то процентном соотношении без потери итогового качества.
  • Если на сайте доступен чат – лучше выставить ограничение на количество «общающихся» пользователей. Если выбранный хостинг бесплатный, установлен не на SSD и плохо справляется с наплывом пользователей.

И еще – в панели администратора или уже на сайте хостинга ежедневно собирается статистика, связанная с запросами и подробностями о круглосуточной активности. Возможно, ресурс сканируют боты или парсеры (а, быть может, и конкуренты) из-за чего и появляется надпись «The Service Is Unavailable». Избежать проблем поможет защита или хотя бы консультация с технической поддержкой хостинга.

Источник

Undefined reference to main c++ [SOLVED]

As a beginner c++ developer , you probably might get error like undefined reference to `main’.

Generally this error occurs when we forgot not define main() function in program. In any c++ program main() function is necessary to start a program. So whenever you create any class then do not forgot to add main function in your project and then you can call class functions from main.

undefined reference to ‘main’ c++

Output:

Here we have just created class inside our program and not define any main function. So here we are getting error undefined reference to main c++.

SOLUTION : Undefined reference to main c++

We can resolve this error by adding main function inside program.

Also many time possible for new developer of someone coming from C# background that they define main() function inside class. So just remember that we have to define main() function as a global in C++.

undefined reference to func() c++

When we declare and function but not added it’s definition then we get undefined reference to func c++ error.

Here we will get error by compiler :

Compilation failed due to following error(s). main.cpp:(.text+0x5): undefined reference to `func()’

SOLUTION : Undefined reference to function c++

We can resolve it by adding c++ function definition.

CONCLUSION:

Make sure in c++ whenever you are getting any compilation errors like undefined reference to main c++ or undefined reference to func c++ ( here func can be any name of function.) then you have to add definition of that function inside your file. Once you have added definition of function then you will not get any undefined reference c++ error and program will be executed successfully.

Reader Interactions

Leave a Reply Cancel reply

Search here

SEE MORE

Fibonacci sequence c++

Fibonacci Sequence c++ is a number sequence which created by sum of previous two numbers. First two number of series are 0 and 1. And then using these two number Fibonacci series is create like 0, 1, (0+1)=1, (1+1)=2, (2+1)=3, (2+3)=5 …etc Displaying Fibonacci Series in C++ ( without recursion) Output: From given output we […]

C++ Map [Learn by Example]

C++ map is part of Standard Template Library (STL). It is type of Associative container. Map in c++ is used to store unique key and it’s value in data structure. But if you want to store non-unique key value then you can use Multi Map in c++. Let us first understand in detail what is […]

how to copy paste in turbo c++ ?

There are many different C++ IDE are available but still many students are using Turbo c++ for learning c/c++ programming languages. During using Turbo c++ if you are beginner you will be confuse for how to copy and paste in turbo c++ or if you have already copy some content and you want to paste […]

return 0 c++

There are two different scenario return statement is used inside c++ programming. We can use return 0 c++ inside main() function or other user defined functions also. But both have different meanings. return 0 c++ used inside Main function return 0 c++ used inside other user defined function What is meaning of return 0 and […]

c++ expected a declaration [ SOLVED]

When any function or statement is not in scope or we have used wrong syntax then possibly you will get error for c++ expected a declaration in your code. Main reasons for errors are: Incorrect use/declaration inside namespace Statements are added out of scope Required statement need to add inside main/function Solution-1 | Expected a […]

Источник

Need urgent help compile issue

Pages: 12

I got below errors while run the code. any ideawhat are these errors?
I use c++14.

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <vector>
#include <memory>
#include <numeric>

using std::cout;
using std::unique_ptr;
using namespace std;

class Shape
{
  public:
    string name;
    double width, height, radius;
  public:
    void set_data (double a, double b)
    {
        width = a;
        height = b;
    }
    virtual double getarea() const = 0;
};

class Rectangle: public Shape
{
public:
    double getarea ()
    {
        return (width * height);
    }
};

class Triangle: public Shape
{
public:
    double getarea ()
    {
        return (width * height)/2;
    }
};

class Circle : public Shape
{
  public:
    double getarea ()
    {
        return 3.1415 * (radius * radius);
    }
};

int main() {
    
    int rectHeight = 0, rectWidth = 0;
    int triaHeight = 0, triaWidth = 0;
    int circRadius = 0;

    std::cin >> rectHeight >> rectWidth >> triaHeight >> triaWidth >> circRadius;

    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.emplace_back(std::make_unique<Rectangle>(rectHeight, rectWidth));
    shapes.emplace_back(std::make_unique<Triangle>(triaHeight, triaWidth));
    shapes.emplace_back(std::make_unique<Circle>(circRadius));
    
    const int totalArea = std::accumulate(shapes.begin(), shapes.end(), 0, [](int total, const auto& shape)
            { return total + shape->getarea(); });
    std::cout << totalArea << "n";

    return 0;
}

Below are the errors:

Compilation failed due to following error(s).In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& …) [with _Tp = Rectangle; _Args = {int&, int&}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<Rectangle, std::default_delete<Rectangle> >]’:
<span class=»error_line» onclick=»ide.gotoLine(‘main.cpp’,60)»>main.cpp:60:74</span>: required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Rectangle’
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)…)); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:24:7: note: because the following virtual functions are pure within ‘Rectangle’:
class Rectangle: public Shape
^~~~~~~~~
main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& …) [with _Tp = Triangle; _Args = {int&, int&}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<Triangle, std::default_delete<Triangle> >]’:
<span class=»error_line» onclick=»ide.gotoLine(‘main.cpp’,61)»>main.cpp:61:73</span>: required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Triangle’
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)…)); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:33:7: note: because the following virtual functions are pure within ‘Triangle’:
class Triangle: public Shape
^~~~~~~~
main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^~~~~~~
In file included from /usr/include/c++/6/memory:81:0,
from main.cpp:3:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& …) [with _Tp = Circle; _Args = {int&}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<Circle, std::default_delete<Circle> >]’:
<span class=»error_line» onclick=»ide.gotoLine(‘main.cpp’,62)»>main.cpp:62:60</span>: required from here
/usr/include/c++/6/bits/unique_ptr.h:795:30: error: invalid new-expression of abstract class type ‘Circle’
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)…)); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:42:7: note: because the following virtual functions are pure within ‘Circle’:
class Circle : public Shape
^~~~~~
main.cpp:21:20: note: virtual double Shape::getarea() const
virtual double getarea() const = 0;
^~~~~~~

Last edited on

Note you should be getting several warnings that give you valuable hints as to what is wrong, never ignore warnings.

The first thing I would recommend is that you comment out the code in main after your «cin» statement and just create one instance of one of your classes. For example «Rectangle test(rectHeight, rectWidth);» , get that one line to compile correctly before you try to complicate things with the vector and the unique_ptr.

With just that one instance here are the messages I get:

||=== Build: Debug in c++homework (compiler: GNU GCC Compiler) ===|
/main.cpp|10|warning: ‘class Shape’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|24|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|24|warning: ‘class Rectangle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|33|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|33|warning: ‘class Triangle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|42|warning: base class ‘class Shape’ has accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp|42|warning: ‘class Circle’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]|
/main.cpp||In function ‘int main()’:|
/main.cpp|58|error: no matching function for call to ‘Rectangle::Rectangle(int&, int&)’|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle()’|
/main.cpp|24|note: candidate expects 0 arguments, 2 provided|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle(const Rectangle&)’|
/main.cpp|24|note: candidate expects 1 argument, 2 provided|
/main.cpp|24|note: candidate: ‘Rectangle::Rectangle(Rectangle&&)’|
/main.cpp|24|note: candidate expects 1 argument, 2 provided|
/main.cpp|58|error: cannot declare variable ‘test’ to be of abstract type ‘Rectangle’|
/main.cpp|24|note: because the following virtual functions are pure within ‘Rectangle’:|
/main.cpp|21|note: ‘virtual double Shape::getarea() const’|
||=== Build failed: 2 error(s), 7 warning(s) (0 minute(s), 1 second(s)) ===|

Fixing those warnings is very important. You also seem to need several constructor and destructors.

If I comment below lines, I can see the below error. Can you provide some inputs here?

//std::vector<std::unique_ptr<Shape>> shapes;
//shapes.emplace_back(std::make_unique<Rectangle>(rectHeight, rectWidth));
//shapes.emplace_back(std::make_unique<Triangle>(triaHeight, triaWidth));
//shapes.emplace_back(std::make_unique<Circle>(circRadius));

Below is the error.

main.cpp: In function ‘int main()’:
main.cpp:66:43: error: ‘shapes’ was not declared in this scope
const int totalArea = std::accumulate(shapes.begin(), shapes.end(), 0, [](int total, const auto& shape)

Minor: Lines 6-7 are unnecessary if you’re going to bring in the entire std namespace at line 8. Suggestion: Change line 8 to using std::string;

Line 21 is a pure virtual function making Shape an abstract class. The compiler is telling you you can’t instantiate a Rectangle because Shape is an abstract class. This is because there is no overload in Rectangle because there is no overload for line 21. Note that line 27 does not overload line 21 because of a difference in constness of the two functions.

Line 36: Ditto

Line 45: Ditto

Line 60: You’re trying to construct a Rectangle with 2 arguments. Rectangle has no such constructor.

Line 61: Ditto

Line 62: Ditto

Line 68: totalArea is an int. getArea() return a double.

I have made the below changes, please check the code. I am not sure why again those errors are seen here? please help me.

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <vector>
#include <memory>
#include <numeric>

using std::string;
constexpr double pi {3.1415926535897932384626643383279502884};

struct Pos
{
    int m_x;
    int m_y;
    Pos(const int x, const int y):m_x{x}, m_y{y} {}
};

class Point {
    private: int m_x;
             int m_y;
    public: Point(const Pos& posi): m_x{posi.m_x}, m_y{posi.m_y}{}
    Point() = default;
    int get_x_coord() const {return m_x;}
    int get_y_coord() const {return m_y;}
};

class Shape
{
  protected:
  double width, height;
  Point m_posit;
  Shape(const Point& posi): m_posit{posi} {}

  public:
    void set_data (double a, double b)
    {
        width = a;
        height = b;
    }
    virtual ~Shape() = default;
    virtual double getarea() const = 0;
};


class Rectangle: public Shape
{
private:
double m_width;
double m_height;

public:
    Rectangle(const Point& posi, const double width = 1.0, const double height = 1.0);
    double getarea() const override {return m_width * m_height;}
};

class Triangle: public Shape
{
public:
    double getarea ()
    {
        return (width * height)/2;
    }
};

class Circle : public Shape
{
  protected: 
    double m_radius;
    
  public:
    Circle(const Point& center, const double radius): Shape{center}, m_radius{radius} {}
    double getarea() const override {return pi* m_radius *m_radius;}
};


std::vector<Point> get_points();
std::vector<std::unique_ptr<Shape> get_shapes(const std::vector<Point>& points);

int main() {
    
    std::vector<Point> points{ get_points() };
    std::vector<std::unique_ptr<Shape> shapes {get_shapes(points)};
    int rectHeight = 0, rectWidth = 0;
    int triaHeight = 0, triaWidth = 0;
    int circRadius = 0;

    std::cin >> rectHeight >> rectWidth >> triaHeight >> triaWidth >> circRadius;
}

 std::vector<Point> get_points()
    {
        std::vector<Point> points
        {
            Point{Pos{0,0}}, Point{Pos{-100,-100}}, Point{Pos{300,300}}
        };
        return points;
    }
    
    std::vector<std::unique_ptr<Shape>> get_shapes(const std::vector<Point>& points)
    {
       std::vector<std::unique_ptr<Shape>> shapes 
       {
           std::make_unique<Rectangle>(rectHeight, rectWidth);
           std::make_unique<Triangle>(triaHeight, triaWidth);
           std::make_unique<Circle>(circRadius);
       };
       return shapes;
    }
    
    const int totalArea = std::accumulate(shapes.begin(), shapes.end(), 0, [](int total, const auto& shape)
            { return total + shape->getarea(); });
    std::cout << totalArea << "n";

    return 0;
}

Last edited on

Perhaps:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <memory>
#include <numeric>
//#include <string>

class Shape {
protected:
	//std::string name;
	double width {}, height {}, radius {};

public:
	Shape(double w, double h) : width(w), height(h) {}
	Shape(double r) : radius(r) {}
	virtual ~Shape() {}

	void set_data(double a, double b) {
		width = a;
		height = b;
	}

	virtual double getarea() const = 0;
};

class Rectangle : public Shape {
public:
	Rectangle(double w, double h) : Shape(w, h) {}

	double getarea() const override { return width * height; }
};

class Triangle : public Shape {
public:
	Triangle(double w, double h) : Shape(w, h) {}

	double getarea() const override { return (width * height) / 2; }
};

class Circle : public Shape {
public:
	Circle(double r) : Shape(r) {}

	double getarea() const override { return 3.1415 * (radius * radius); }
};

int main()
{
	double rectHeight {}, rectWidth {};
	double triaHeight {}, triaWidth {};
	double circRadius {};

	std::cout << "Enter rect height, rect width, tri height, tri width, circ rad: ";

	std::cin >> rectHeight >> rectWidth >> triaHeight >> triaWidth >> circRadius;

	std::vector<std::unique_ptr<Shape>> shapes;

	shapes.emplace_back(std::make_unique<Rectangle>(rectHeight, rectWidth));
	shapes.emplace_back(std::make_unique<Triangle>(triaHeight, triaWidth));
	shapes.emplace_back(std::make_unique<Circle>(circRadius));

	const auto totalArea {std::accumulate(shapes.begin(), shapes.end(), 0.0, [](auto total, const auto& shape)
			{ return total + shape->getarea(); })};

	std::cout << totalArea << 'n';
}

Last edited on

Below are compiler errors seen:

main.cpp: In function ‘int main()’:
main.cpp:85:43: error: ‘get_points’ was not declared in this scope
std::vector<Point> points{ get_points() };
^
main.cpp:85:45: error: no matching function for call to ‘std::vector::vector()’
std::vector<Point> points{ get_points() };
^
In file included from /usr/include/c++/6/vector:64:0,
from main.cpp:10:
/usr/include/c++/6/bits/stl_vector.h:403:9: note: candidate: template std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const allocator_type&)
vector(_InputIterator __first, _InputIterator __last,
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:403:9: note: template argument deduction/substitution failed:
/usr/include/c++/6/bits/stl_vector.h:375:7: note: candidate: std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(initializer_list<value_type> __l,
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:375:7: note: conversion of argument 1 would be ill-formed:
/usr/include/c++/6/bits/stl_vector.h:350:7: note: candidate: std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>&&, const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(vector&& __rv, const allocator_type& __m)
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:350:7: note: candidate expects 2 arguments, 1 provided
/usr/include/c++/6/bits/stl_vector.h:341:7: note: candidate: std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&, const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(const vector& __x, const allocator_type& __a)
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:341:7: note: candidate expects 2 arguments, 1 provided
/usr/include/c++/6/bits/stl_vector.h:337:7: note: candidate: std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>&&) [with _Tp = Point; _Alloc = std::allocator]
vector(vector&& __x) noexcept
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:337:7: note: conversion of argument 1 would be ill-formed:
/usr/include/c++/6/bits/stl_vector.h:320:7: note: candidate: std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = Point; _Alloc = std::allocator]
vector(const vector& __x)
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:320:7: note: conversion of argument 1 would be ill-formed:
/usr/include/c++/6/bits/stl_vector.h:291:7: note: candidate: std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const value_type&, const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = Point; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(size_type __n, const value_type& __value,
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:291:7: note: candidate expects 3 arguments, 1 provided
/usr/include/c++/6/bits/stl_vector.h:279:7: note: candidate: std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(size_type __n, const allocator_type& __a = allocator_type())
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:279:7: note: conversion of argument 1 would be ill-formed:
/usr/include/c++/6/bits/stl_vector.h:266:7: note: candidate: std::vector<_Tp, _Alloc>::vector(const allocator_type&) [with _Tp = Point; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::allocator_type = std::allocator]
vector(const allocator_type& __a) _GLIBCXX_NOEXCEPT
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:266:7: note: conversion of argument 1 would be ill-formed:
/usr/include/c++/6/bits/stl_vector.h:255:7: note: candidate: std::vector<_Tp, _Alloc>::vector() [with _Tp = Point; _Alloc = std::allocator]
vector()
^~~~~~
/usr/include/c++/6/bits/stl_vector.h:255:7: note: candidate expects 0 arguments, 1 provided
main.cpp:86:40: error: template argument 1 is invalid
std::vector<std::unique_ptr<Shape> shapes {get_shapes(points)};
^~~~~~
main.cpp:86:40: error: template argument 2 is invalid
main.cpp:86:65: error: ‘get_shapes’ was not declared in this scope
std::vector<std::unique_ptr<Shape> shapes {get_shapes(points)};
^
main.cpp:93:5: error: a function-definition is not allowed here before ‘{’ token
{
^
main.cpp:117:1: error: expected ‘}’ at end of input
}

See my previous post.

Hi seeplus

Your code compiles fine with no errors.
But while I try to provide input as below,
Input
4 3 5 2 5

Enter rect height, rect width, tri height, tri width, circ rad: 95.5375

Here for example, for values 4 and 3, area of rect must be 12 (since h = 4, w = 3 as per input given by user). Similarly for tri area must be 5 ( for h =5, w = 2). Also for circ area must be 79 (for rad = 5 here as input). So total area of shapes is 96, but as per compiler output I get 95.5375 only.

My code above works in double as per your original code — not int.

Is there any way to get 96 as total area instead if 95.5375? can i use round of function?

Last edited on

Do you mean to add this line?
std::cout << std::fixed
<< «ceil(totalArea) = » << std::ceil(totalArea) << ‘n’;

But I get compiler output as below. Here it gives 95.000000. For example, if it gives 95.5375, then I need to round of to nearest int, which is 96, instead of 95. i want to round a double to nearest int .How can i do this?
Enter rect height, rect width, tri height, tri width, circ rad: 4 3 5 2 5
ceil(totalArea) = 95.000000

Last edited on

std::ceil should print out 96.000000. So did it in my testrun of seeplus’ code example.
if you want to round down, use floor
if you want to round up, use ceil
if you want to round to the nearest int, use round.

Ok, so for 95.5375, to truncate and get 96, should I use ceil? I am still not clear what you said here. if you tried with any sample code, feel free to share here.

Last edited on

Denver2020,

WHY do you want to round an area to the nearest integer? If you had a circle of radius 0.1 how big do you think that area would be?

If you are still hell-bent on doing it then JustShinigami has told you exactly which choices of function you need: is it so difficult to call those functions?

If it is purely for «pretty» output then simply set the precision to whatever you want when outputting.

The reason is im trying to run test and it fails, because not being integer value. As you can see the test expects output to be 96, but compiler output it as 95.5375. Please help me on this.

Input (stdin)

4 3 5 2 5
Your Output (stdout)
Enter rect height, rect width, tria height, tria width, circ rad: 95.5375

Expected Output
96

Last edited on

Take your pick.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
   double x = 95.5375;
   cout << x << 'n';
   cout << round( x ) << 'n';
   cout << ceil( x ) << 'n';
   cout << (int)( x + 0.5 ) << 'n';
   cout << fixed << setprecision( 0 ) << x << 'n';
}

Thanks for the quick tips.
After modifying the code, I got the below output, but test still fails.

Here in the code, created shape interface which has abstract function getarea() must have integer return value. But in the actual code its double. The integer values needed to calculate area for each of these shapes will be provided to constructor of each shape and then need to round result to nearest integer value before returning it. could this be the reason for test failure?

Input (stdin)

4 3 5 2 5
Your Output (stdout)
Enter rect height, rect width, tria height, tria width, circ rad: 96

Expected Output
96

Well if the expected output is

and your code produces

and the test says

then I should ask for your money back!

Pages: 12

Topic: Pascal error troubleshooting  (Read 982 times)

Greeting all, I hope everyone is staying safe.

I am kindly asking for some help… to get my code running
— Thanks

program Refund Status;
Var
Candidates:  integer;
RefundsReceived: integer;
CandidateName:  string;
VotesReceived:  integer;
VotesCast:  integer;
Percentage:  real;

Begin
   writeln(‘Welcome’)
   writeln(‘Enter appropriate responses for an accurate result’)
   for Candidates:=1 to 10 do
    begin
      writeln(‘Enter Candidate name’);
      readln(CandidateName);
      writeln;
      writeln(‘Enter Candidate votes received’);
      readln(VotesReceived);
      writeln;
      writeln(‘Enter Constituency’s Votes Cast’);
      readln(VotesCast)
      writeln;
      Percentage  :=(Candidate’sVotesReceived/Constituency’sVotesVast)*100;
      writeln;
              if Percentage>=20% then
   begin
      writeln(‘Refund Due for ’,Candidate’sName);
      Candidates  := Candidates + 1
   end
             else
   begin
      writeln(‘No Refund’)
   end;
    end;
      writeln(‘The number of candidates who received a refund is ’,RefundsReceived);
End.


Logged


I can see this is a school project  :D

First off, use    ‘ your text ‘   instead of what you are doing…don’t use ` and the other one I can’t seem to reproduce from my keyboard.

 come back when you have that one figured out and put your code within a pound symbol as you can see above » # «

Thank you for your services, have a nice day.


Logged

The only true wisdom is knowing you know nothing



Logged


Please help… I attached a screenshot with the error messages

As said, use code-tags (https://wiki.freepascal.org/Forum#Use_code_tags). The very first character is throwing you an error but we have no way of knowing what that character might be.

  1. program RefundStatus;

  2. {$mode objfpc}{$H+}

  3. uses

  4. {$IFDEF UNIX}{$IFDEF UseCThreads}

  5.   cthreads,

  6. {$ENDIF}{$ENDIF}

  7.   Classes

  8. { you can add units after this };

  9. begin

  10. Program RefundStatus;

  11. Var

  12.     Candidates:integer;

  13.     RefundsReceived: integer;

  14.     CandidateName:  string;

  15.     VotesReceived:  integer;

  16.     VotesCast:  integer;

  17.     Percentage:  real;

  18. begin candidates:=1;

  19. Begin

  20. for Candidates:=1 to 10 do ;

  21. Write(‘Welcome’);

  22. Write(‘Enter appropriate responses for an accurate result’);

  23. for Candidates:=1 to 10 do ;

  24. begin

  25. writeln(‘Enter Candidate name’);

  26. readln(CandidateName);

  27. writeln;

  28. writeln(‘Enter Candidate votes received’);

  29. readln(VotesReceived);

  30. writeln;

  31. writeln(‘Enter Constituency Votes Cast’);

  32. readln(VotesCast);

  33. Writeln;

  34.                 Percentage  :=(VotesReceived/ VotesCast)*100;

  35. writeln;

  36. if Percentage>=20 then

  37. begin

  38. writeln(‘Refund Due for’ , ‘Candidates Name’);

  39.                 Candidates  := Candidates + 1

  40. end

  41. else

  42. begin

  43. writeln(‘No Refund’)

  44. end;

  45. end;

  46. writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);

  47. End;

  48. end.

edit:
And when there is no (strange) character messing things up the fpc commandline compiler throws:

Compiling RefundStatus.pas
RefundStatus.pas(15,7) Error: Illegal expression
RefundStatus.pas(15,15) Fatal: Syntax error, ";" expected but "identifier REFUNDSTATUS" found
Fatal: Compilation aborted
Error: ppcarm returned an error exitcode
Compilation failed.

Which is to be expected  :)

In case you might be wondering why then please read https://wiki.freepascal.org/Program_Structure and https://wiki.lazarus.freepascal.org/Program so that you are able to address the issue.

« Last Edit: May 23, 2020, 06:03:34 am by TRon »


Logged



Logged


I added the tags for clarity

  1. program RefundStatus;

  2. {$mode objfpc}{$H+}

  3. uses

  4. {$IFDEF UNIX}{$IFDEF UseCThreads}

  5.   cthreads,

  6. {$ENDIF}{$ENDIF}

  7.   Classes

  8. { you can add units after this };

  9. begin

  10. Program RefundStatus;

  11. Var

  12.     Candidates:integer;

  13.     RefundsReceived: integer;

  14.     CandidateName:  string;

  15.     VotesReceived:  integer;

  16.     VotesCast:  integer;

  17.     Percentage:  real;

  18. begin candidates:=1;

  19. Begin

  20. for Candidates:=1 to 10 do ;

  21. Write(‘Welcome’);

  22. Write(‘Enter appropriate responses for an accurate result’);

  23. for Candidates:=1 to 10 do ;

  24. begin

  25. writeln(‘Enter Candidate name’);

  26. readln(CandidateName);

  27. writeln;

  28. writeln(‘Enter Candidate votes received’);

  29. readln(VotesReceived);

  30. writeln;

  31. writeln(‘Enter Constituency Votes Cast’);

  32. readln(VotesCast);

  33. Writeln;

  34.                 Percentage  :=(VotesReceived/ VotesCast)*100;

  35. writeln;

  36. if Percentage>=20 then

  37. begin

  38. writeln(‘Refund Due for’ , ‘Candidates Name’);

  39.                 Candidates  := Candidates + 1

  40. end

  41. else

  42. begin

  43. writeln(‘No Refund’)

  44. end;

  45. end;

  46. writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);

  47. End;

  48. end.


Logged


Thanks TRon

If you are able to ‘fix’ the structural issues, then we can help you with actual implementation related issues.

Because you are doing a homework assignment we simply can’t provide a literal answer (well, we could but what good would that do you).

That means that in case your code isn’t exactly doing what you expected it to do then please ask explicit questions (even if you do not know the exact words, then try to describe it), by describing the problem (what you have written, what you expected the code to do and what the code is actually doing (wrong) for you. That way you are able to get the quickest answer (and learn the fastest).

I added the tags for clarity

There you go, looking a lot nicer don’t you think ? :-)

Are you still presented with the same error ? Because that could suggest there is something wrong that is not even related to code whatsoever.

fwiw: if i copy-paste the code (between the code-tags) you just posted then there is nothing wrong with it. In worst case, copy-paste it yourself back in your editor and save it before compiling.


Logged


For help with the structural issues in the program code, you could start with the Wiki’s Basic Pascal Tutorial’s «Hello, World» and the pages that follow.


Logged

Lazarus 2.3, FPC 3.3.1 macOS 12.6.1 x86_64 Xcode 14.1
Lazarus 2.3, FPC 3.3.1 macOS 12.6.1 aarch64 Xcode 14.1


I am kindly asking for some help… to get my code running

Tehnicly you did it yourself.
Your version of running code:

  1. Program RefundStatus;

  2. Var

  3.     Candidates:integer;

  4.     RefundsReceived: integer;

  5.     CandidateName:  string;

  6.     VotesReceived:  integer;

  7.     VotesCast:  integer;

  8.     Percentage:  real;

  9. begin candidates:=1;

  10. for Candidates:=1 to 10 do ;

  11. Write(‘Welcome’);

  12. Write(‘Enter appropriate responses for an accurate result’);

  13. for Candidates:=1 to 10 do ;

  14. begin

  15. writeln(‘Enter Candidate name’);

  16. readln(CandidateName);

  17. writeln;

  18. writeln(‘Enter Candidate votes received’);

  19. readln(VotesReceived);

  20. writeln;

  21. writeln(‘Enter Constituency Votes Cast’);

  22. readln(VotesCast);

  23. Writeln;

  24.                 Percentage  :=(VotesReceived/ VotesCast)*100;

  25. writeln;

  26. if Percentage>=20 then

  27. begin

  28. writeln(‘Refund Due for’ , ‘Candidates Name’);

  29.                 Candidates  := Candidates + 1

  30. end

  31. else

  32. begin

  33. writeln(‘No Refund’)

  34. end;

  35. end;

  36. writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);

  37. end.

1.
To fix it further you have to answer to yourself «what code suppose to do and what output suppose to be?»

2. there are 3 types of «;»  a) statement must end with «;» b) «;» is optional at end of statement c) program behavior dramatically changes by having or not having «;» at the end of the statement

3. learn how to output value of variable (it’s most important thing  if your goal is to learn programing at all)

4.

  1. Candidates  := Candidates + 1

from compiler stand point line is correct. Is it thou?


Logged


Hello,
OnlineGDB Q&A section lets you put your programming query to fellow community users.
Asking a solution for whole assignment is strictly not allowed.
You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.


0 votes



asked

May 22, 2019


by
Romit Shrivastava

(120 points)



closed

Feb 21, 2022


by Admin


Compilation failed due to following error(s).

Main.java:5: error: error while writing Main: No space left on device
class Main
^
1 error

closed with the note:

answered

  • java

2 Answers


0 votes



answered

May 22, 2019


by
Admin

(4,960 points)



It has been issue on server side, which is resolved now.


+2 votes



answered

Jun 1, 2019


by
rajesh


memory usage excessed in system

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.

Главная » Решебник Абрамяна » Условный оператор: группа If (1-30) » If4. Решебник Абрамяна М. Э.

If4. Даны три целых числа. Найти количество положительных чисел в исходном наборе.

Решение Pascal

program If4;

var

  N1, N2, N3, Res : Integer;

begin

  Write(‘Введите перовое целое число: ‘);

  Readln(N1);

  Write(‘Введите второе целое число: ‘);

  Readln(N2);

  Write(‘Введите третье целое число: ‘);

  Readln(N3);

  Res:=0;

  if N1>0 then Inc(Res);

  if N2>0 then Inc(Res);

  if N3>0 then Inc(Res);

  writeln(Res);

end.

Решение 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

#include <stdio.h>

int main(void)

{

   int a1, a2, a3;

   printf(«a1:»);

   scanf («%i», &a1);

   printf(«a2:»);

   scanf («%i», &a2);

   printf(«a3:»);

   scanf («%i», &a3);

  if (a1>0) a1=1;

  else a1=0;

  if (a2>0) a2=1;

  else a2=0;

  if (a3>0) a3=1;

  else a3=0;

  printf(«%in»,a1+a2+a3);

  return 0;

}

Решение 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

# include <iostream>

# include <windows.h>

# include <cmath>

using namespace std;

int main ()

{

  SetConsoleCP(1251);

  SetConsoleOutputCP(1251);

  int a,b,c;

  int N = 0;

  cout << «Введите 3 целых числа: « << endl;

  cout << «Введите первое число: «;

  cin >> a;

  cout << «Введите второе число: «;

  cin >> b;

  cout << «Введите третье число: «;

  cin >> c;

  if (a>0) ++N;

  if (b>0) ++N;

  if (c>0) ++N;

  cout << «Количество положительных чисел в исходном наборе : « << N << endl;

  system («pause»);

  return 0;

}

Оцените решение

Загрузка…

If4. Решебник Абрамяна М. Э.: 21 комментарий

  • Программа

    23.09.2019

    Permalink

    Что значит «++N» ?

    Ответ

    • Портал uTeacherАвтор записи

      23.09.2019

      Permalink

      Это префиксная форма инкремента. ++n аналогично n = n+1. В данном случае можете заменить ++n на n = n+1 или n++, результат будет аналогичен.

      Ответ

  • Дмитрий

    18.06.2020

    Permalink

    Почему (в решении С ) а1 і а2 і а3 приравниваем к 1 ?

    Ответ

    • Портал uTeacherАвтор записи

      21.11.2020

      Permalink

      Переменные а1, а2, а3 после выполнения условия if будут содержать количество положительный элементов, в нашем случае это 1.

      Ответ

  • Данила

    18.06.2020

    Permalink

    Почему (в решении С ) в конце пишется команда return 0 ? Можно ли просто getchar() ?

    Ответ

    • Портал uTeacherАвтор записи

      21.11.2020

      Permalink

      Функция main объявлена как тип int, поэтому оператор «return 0» обязательный, т.к. необходимо вернуть результат. А вот строку «system («pause»);» можно заменить на «getchar();»

      Ответ

  • Матвей

    14.02.2021

    Permalink

    где решение для файтон?

    Ответ

  • Аноним

    06.06.2021

    Permalink

    где? C#

    Ответ

    • Ulugbek C#

      26.08.2022

      Permalink

      int a, b, c, n;
      Console.Write(«A: «);
      a = Convert.ToInt16(Console.ReadLine());
      Console.Write(«B: «);
      b = Convert.ToInt16(Console.ReadLine());
      Console.Write(«C: «);
      c = Convert.ToInt16(Console.ReadLine());
      n = 0;
      if (a > 0) ++n;
      if (b > 0) ++n;
      if (c > 0) ++n;

      Console.WriteLine(«N: » + n);

      Ответ

  • Диас Сайдахмет

    05.02.2022

    Permalink

    В коде для С++ ошибка
    Compilation failed due to following error(s). 2 | # include
    | ^~~~~~~~~~~
    compilation terminated.
    Пишет что библиотеки windows.h не существует

    Ответ

  • З|Ф

    23.06.2022

    Permalink

    а можно на JavaScript пожалуйста

    Ответ

    • Бот

      14.07.2022

      Permalink

      let a = +prompt(‘Введите число’,»);
      let b = +prompt(‘Введите число’,»);
      let c = +prompt(‘Введите число’,»);
      let x = 0;

      if (a>0) {
      a = x + 1;
      } else (a=0);

      if (b>0) {
      b = x + 1;
      } else (b=0);

      if (c>0) {
      c = x + 1;
      } else (c = 0);

      alert(a + b + c);

      Возможно так

      Ответ

      • Бот

        14.07.2022

        Permalink

        Только где else скобки на фигурные поменять

        Ответ

  • Ulugbek C#

    26.08.2022

    Permalink

    int a, b, c, n;
    Console.Write(«A: «);
    a = Convert.ToInt16(Console.ReadLine());
    Console.Write(«B: «);
    b = Convert.ToInt16(Console.ReadLine());
    Console.Write(«C: «);
    c = Convert.ToInt16(Console.ReadLine());
    n = 0;
    if (a > 0) ++n;
    if (b > 0) ++n;
    if (c > 0) ++n;

    Console.WriteLine(«N: » + n);

    Ответ

    • Анастасия

      21.09.2022

      Permalink

      Переменной n не присвоен тип данных (допустим стоит присвоить тип int) не мешает ли это работе программы и почему такие действия возможны?

      Ответ

    • Kuba

      02.01.2023

      Permalink

      Он в свмом начале обьявил все переменные ( int a, b, c, n;) и только поптом использовал.

      Ответ

  • 30.11.2022

    Permalink

    package abramyan.If;
    import java.util.Scanner;

    public class If4 {
    public static void main(String[] args) {

    int a, b, c, count=0;

    Scanner scanner = new Scanner(System.in);

    System.out.print(«a = «);
    a = scanner.nextInt();

    System.out.print(«b = «);
    b = scanner.nextInt();

    System.out.print(«c = «);
    c = scanner.nextInt();

    if(a > 0) ++count;
    if(b > 0) ++count;
    if(c > 0) ++count;

    System.out.println(«count = » + count);
    scanner.close();

    }
    }

    Ответ

  • Danel Yermekbay java

    01.12.2022

    Permalink

    import java.util.Scanner;
    public class if4 {

    public static void main(String[] args) {

    int a, b, c, count=0;

    Scanner scanner = new Scanner(System.in);

    System.out.print(«a = «);
    a = scanner.nextInt();

    System.out.print(«b = «);
    b = scanner.nextInt();

    System.out.print(«c = «);
    c = scanner.nextInt();

    if(a > 0) ++count;
    if(b > 0) ++count;
    if(c > 0) ++count;

    System.out.println(«katar = » + count);
    scanner.close();

    }
    }

    Ответ

  • Алмат Тулкибаев (java)

    18.01.2023

    Permalink

    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    int d = 0;
    if (a>0) ++d;
    if (c>0) ++d;
    if (b>0) ++d;
    System.out.println(d);

    Ответ

  • Jahongir JavaScript(VSCode)

    26.01.2023

    Permalink

    let a = +prompt(«A sonni kiriting: «);
    let b = +prompt(«B sonni kiriting: «);
    let c = +prompt(«C sonni kiriting: «);
    let d = 0;

    if (a > 0) {
    a = d + 1;
    } else a = 0;

    if (b > 0) {
    b = d + 1;
    } else b = 0;

    if (c > 0) {
    c = d + 1;
    } else c = 0;

    console.log(a + b + c);

    Ответ

  • Аноним

    30.01.2023

    Permalink

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApp6
    {
    internal class Program
    {
    static void Main(string[] args)
    {
    int a, b, c, n;
    Console.Write(«A: «);
    a = Convert.ToInt32(Console.ReadLine());
    Console.Write(«B: «);
    b = Convert.ToInt32(Console.ReadLine());
    Console.Write(«C: «);
    c = Convert.ToInt32(Console.ReadLine());
    n = 0;
    if (a > 0) ++n;
    if (b > 0) ++n;
    if (c > 0) ++n;

    Console.WriteLine(«N: » +n);
    }
    }
    }
    Почему у меня это не работает?

    Ответ

Добавить комментарий

Понравилась статья? Поделить с друзьями:
  • Compilation error rtc was not declared in this scope
  • Compilation error redefinition of void setup
  • Compilation error python
  • Compilation error pinmode was not declared in this scope
  • Compilation error maven