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 натуральных числа выяснить является ли хоть одно из них палиндромом (перевёртышем) Выяснить, является ли хоть одно из чисел палиндромом Даны три слова. Определить, является ли хоть одно из них палиндромом 5 |
thyrex 11103 / 6337 / 1312 Регистрация: 06.09.2009 Сообщений: 24,072 |
||||
02.02.2022, 15:23 |
2 |
|||
0 |
bormant Модератор 7502 / 4370 / 2776 Регистрация: 22.11.2013 Сообщений: 12,506 Записей в блоге: 1 |
||||||||||||
02.02.2022, 15:35 |
3 |
|||||||||||
Сообщение было отмечено DenGI235 как решение РешениеДругой вариант без копирования строки:
Добавлено через 2 минуты
является ли хоть одно из них палиндромом
Добавлено через 1 минуту
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 |
|||
Другой вариант без копирования строки: или так
Добавлено через 54 секунды
Compilation failed due to following error(s). я там забыл переменные объявить
0 |
Модератор 7502 / 4370 / 2776 Регистрация: 22.11.2013 Сообщений: 12,506 Записей в блоге: 1 |
|
02.02.2022, 15:55 |
6 |
или так в этом варианте деление внутри цикла выглядит не очень здорово.
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
02.02.2022, 15:55 |
Помогаю со студенческими работами здесь Даны два натуральных числа. Выяснить, является ли хоть одно из них палиндромом Выяснить, является ли хоть одно из заданных чисел палиндромом Выяснить, является ли хоть одно из заданных чисел палиндромом Выяснить, является ли хоть одно из трех слов палиндромом Выяснить является ли хоть одно из данных чисел палиндромом(перевёртышем) Выяснить, является ли хоть одно из заданных слов палиндромом (GUI-приложение) Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 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 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 LiamJason Liam
32.4k5 gold badges21 silver badges52 bronze badges
Содержание
- Compilation failed due to following error перевод
- «503 Service Temporarily Unavailable»: перевод, что значит и как исправить
- Причины появления
- Как исправить ошибку
- Как действовать вебмастеру
- Undefined reference to main c++ [SOLVED]
- undefined reference to ‘main’ c++
- SOLUTION : Undefined reference to main c++
- undefined reference to func() c++
- SOLUTION : Undefined reference to function c++
- Reader Interactions
- Leave a Reply Cancel reply
- Primary Sidebar
- Search here
- Social Media
- SEE MORE
- Fibonacci sequence c++
- C++ Map [Learn by Example]
- how to copy paste in turbo c++ ?
- return 0 c++
- 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.
|
|
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.
|
|
Last edited on
Perhaps:
|
|
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.
|
|
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
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);
}
}
}
Почему у меня это не работает?Ответ
Добавить комментарий
Topic: Pascal error troubleshooting (Read 981 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
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.
-
program RefundStatus;
-
{$mode objfpc}{$H+}
-
uses
-
{$IFDEF UNIX}{$IFDEF UseCThreads}
-
cthreads,
-
{$ENDIF}{$ENDIF}
-
Classes
-
{ you can add units after this };
-
begin
-
Program RefundStatus;
-
Var
-
Candidates:integer;
-
RefundsReceived: integer;
-
CandidateName: string;
-
VotesReceived: integer;
-
VotesCast: integer;
-
Percentage: real;
-
begin candidates:=1;
-
Begin
-
for Candidates:=1 to 10 do ;
-
Write(‘Welcome’);
-
Write(‘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 Votes Cast’);
-
readln(VotesCast);
-
Writeln;
-
Percentage :=(VotesReceived/ VotesCast)*100;
-
writeln;
-
if Percentage>=20 then
-
begin
-
writeln(‘Refund Due for’ , ‘Candidates Name’);
-
Candidates := Candidates + 1
-
end
-
else
-
begin
-
writeln(‘No Refund’)
-
end;
-
end;
-
writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);
-
End;
-
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
-
program RefundStatus;
-
{$mode objfpc}{$H+}
-
uses
-
{$IFDEF UNIX}{$IFDEF UseCThreads}
-
cthreads,
-
{$ENDIF}{$ENDIF}
-
Classes
-
{ you can add units after this };
-
begin
-
Program RefundStatus;
-
Var
-
Candidates:integer;
-
RefundsReceived: integer;
-
CandidateName: string;
-
VotesReceived: integer;
-
VotesCast: integer;
-
Percentage: real;
-
begin candidates:=1;
-
Begin
-
for Candidates:=1 to 10 do ;
-
Write(‘Welcome’);
-
Write(‘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 Votes Cast’);
-
readln(VotesCast);
-
Writeln;
-
Percentage :=(VotesReceived/ VotesCast)*100;
-
writeln;
-
if Percentage>=20 then
-
begin
-
writeln(‘Refund Due for’ , ‘Candidates Name’);
-
Candidates := Candidates + 1
-
end
-
else
-
begin
-
writeln(‘No Refund’)
-
end;
-
end;
-
writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);
-
End;
-
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:
-
Program RefundStatus;
-
Var
-
Candidates:integer;
-
RefundsReceived: integer;
-
CandidateName: string;
-
VotesReceived: integer;
-
VotesCast: integer;
-
Percentage: real;
-
begin candidates:=1;
-
for Candidates:=1 to 10 do ;
-
Write(‘Welcome’);
-
Write(‘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 Votes Cast’);
-
readln(VotesCast);
-
Writeln;
-
Percentage :=(VotesReceived/ VotesCast)*100;
-
writeln;
-
if Percentage>=20 then
-
begin
-
writeln(‘Refund Due for’ , ‘Candidates Name’);
-
Candidates := Candidates + 1
-
end
-
else
-
begin
-
writeln(‘No Refund’)
-
end;
-
end;
-
writeln(‘The number of candidates who received a refund is ‘, ‘RefundsReceived’);
-
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.
-
Candidates := Candidates + 1
from compiler stand point line is correct. Is it thou?
Logged
- Forum
- C et C++
- C++
- D�buter
- Compilation failed due to following error(s)
Sujet :
C++
-
28/01/2021, 04h33
#1
Nouveau Candidat au Club
Compilation failed due to following error(s)
Bonjour
SVP je suis bloqu� j’arrive pas � comprendre mes fautes
je suis en train de compiler ce programme pour dessiner une matrice adjacente.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#include <iostream> #include <iomanip> using namespace std ; // A function to print the adjacency matrix. void PintMat(int mat[][10],int n){ int i,j; cout<<"nn"<<setw(4)<<" "; for(i=0;i<n; i++) cout<<setw(3)<<"("<<i+1<<")"; cout<<"nn"; //Print 1 if the corresponding vertexesare connected otherwise 0. for(i=0;i<n;i++){ cout<<setw(3)<<"("<<i+1<<")"; for(j=0;j<n;j++){ cout<<setw(4)<<mat[i][j]; } cout<<"nn"; } main(){ int i,j,v; cout<<"enter the number of vertexes:"; cin>>v; int mat[10][10] cout<<"n"; //Take input of the adjacency of each pair of vertexes. for(i=0;i<v;i++){ for (j=i;j<v;j++){ if(i!=j){ cout<<"enter 1 if vertex"<<i+1<<"is adjacent to"<<j+1<<" , otherwise 0: "; cin>>mat[i][j]; mat[i][j]=mat[i][j]; } else mat[i][j]=0; } } PrintMat(mat,v); return 0; } //Lets run the program.
Je recois ces messages :
1
2
3
4
5
6Compilation failed due to following error(s).main.cpp: In function ‘void PintMat(int (*)[10], int)’: main.cpp:26:6: error: ‘main’ was not declared in this scope main(){ ^ main.cpp:47:1: error: expected ‘}’ at end of input }
-
28/01/2021, 16h06
#2
Ton code est tellement mal �crit que tu vois m�me pas o� se finissent les accolades, si tent� qu’elles se finissent.
C’est extraordinaire de pouvoir �crire un code aussi moche, ou de le copier aussi mal, alors qu’il suffit de 2ms dans un navigateur ou un �diteur pour le formater proprement.
+ R�pondre � la discussion
Cette discussion est r�solue.
- Forum
- C et C++
- C++
- D�buter
- Compilation failed due to following error(s)
Discussions similaires
-
R�ponses: 5
Dernier message: 04/11/2016, 13h04
-
R�ponses: 5
Dernier message: 09/06/2015, 08h39
-
R�ponses: 8
Dernier message: 20/04/2009, 11h14
-
R�ponses: 1
Dernier message: 18/07/2008, 21h23
-
R�ponses: 5
Dernier message: 04/12/2005, 07h01