AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||
1 |
||||
09.01.2017, 22:14. Показов 5956. Ответов 21 Метки нет (Все метки)
У меня vs 2015 c++. Необходимо создать шаблон класса для представления 2-х компонентных комплексных чисел и реализовать перегруженные операторы для всех стандартных операций и т.д.
При запуске вылетает с ошибками: Понятно, что он хочет return , но чего и зачем непонятно…
__________________
0 |
2431 / 1831 / 404 Регистрация: 15.12.2013 Сообщений: 8,166 |
|
09.01.2017, 22:30 |
2 |
Понятно, что он хочет return , но чего и зачем непонятно… Если вам return не нужен, то поставьте
0 |
IGPIGP Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
||||
10.01.2017, 01:22 |
3 |
|||
Сообщение было отмечено AlisaChoi как решение Решение
1 |
AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||
10.01.2017, 21:49 [ТС] |
4 |
|||
Если вам return не нужен, то поставьте void и ничего не возвращайте. Он все равно просил return..
Спасибо за помощь) Заработало! Буду добавлять остальные запросы для этой проги)
0 |
Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
|
10.01.2017, 21:52 |
5 |
Заработало! Сам люблю этот момент.)
0 |
AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||||||
11.01.2017, 23:05 [ТС] |
6 |
|||||||
Пишите. Вопрос все же возник при добавлении разнообразия в прогу. Сравнение на равенство прошло хорошо, а вот с вычислением модуля (а далее преобразование по формуле Эйлера) пошло как-то не очень.
так и
Но он требует задать или сам модуль или корень.
0 |
2431 / 1831 / 404 Регистрация: 15.12.2013 Сообщений: 8,166 |
|
11.01.2017, 23:42 |
7 |
Для модуля можно ж использовать как Вы сравните возвращаемые значения.
А каким образом это можно прописать с оператором? Или вообще каким образом это выявляется? Что вы понимаете под словом «это». Сформулируйте свои вопросы так, чтобы было понятно о чем речь.
0 |
0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
|
11.01.2017, 23:55 [ТС] |
8 |
Что вы понимаете под словом «это». Сформулируйте свои вопросы так, чтобы было понятно о чем речь. Пардон. Мне не понятно как объявить модуль, как его записать..
0 |
IGPIGP Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
||||
12.01.2017, 00:01 |
9 |
|||
Пардон. Мне не понятно как объявить модуль, как его записать.. Поскольку такого оператора нет то можно:
или в этом роде
1 |
S_el 2431 / 1831 / 404 Регистрация: 15.12.2013 Сообщений: 8,166 |
||||
12.01.2017, 00:02 |
10 |
|||
AlisaChoi, одним полноценным шаблоном, возвращающим тип double.
раз это шаблон-член, то аргумент можно и не передавать.
1 |
AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||
12.01.2017, 17:54 [ТС] |
11 |
|||
C++Выделить код
Простите за безграмотность, но выпадает ошибка C2039 modulus: не является членом «Complex<T>»
0 |
IGPIGP Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
||||
12.01.2017, 19:04 |
12 |
|||
Простите за безграмотность, но выпадает ошибка C2039 modulus: не является членом «Complex<T>» в области класса (в public) напишите:
ну, то есть, это просто метод, а не оператор и его нужно будет вызывать на экземпляре оператором доступа (точкой) как и любой метод. А имя можно и другое придумать
0 |
0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
|
12.01.2017, 19:20 [ТС] |
13 |
в области класса (в public) напишите Спасибо! Теперь снова заработало буду разбираться с выводом модуля и преобразованием Эйлера сейчас..
0 |
Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
|
12.01.2017, 19:23 |
14 |
Просто во всем не очень-то бум-бум.. Поэтому легкие программы все равно идут туго и требуют долгого времени на разбирательство.. Но это до жути интересно) Это всё ну, прямо, про меня.
0 |
AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||||||
13.01.2017, 19:17 [ТС] |
15 |
|||||||
Пишите. И возник очередной вопрос)
Комплекс все тот же (присутствует сравнение на равенство и модуль, но значения пока не выводят) Кликните здесь для просмотра всего текста
0 |
IGPIGP Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
||||
13.01.2017, 21:24 |
16 |
|||
AlisaChoi, возможность создавать комплексные числа на параметрах int, char, string и т.п это зло. Самый простой вариант для сложения инстансов разных типов:
Но сложение, где первым слагаемым будет более узкий тип, будет приводить к усечению. Такое поведение интуитивно-живодерно-обрезающее и будет приводить к травмам.
0 |
AlisaChoi 0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
||||||||
13.01.2017, 22:57 [ТС] |
17 |
|||||||
Самый простой вариант для сложения инстансов разных типов Что-то он немного вылетел у меня с ошибкой.. сначала, что
забыли.. а потом, что cout, endl и system не объявлены.
перенести отдельно (как делали до этого) ?
0 |
Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
|
13.01.2017, 23:00 |
18 |
забыли.. а потом, что cout, endl и system не объявлены. я написал чтобы было понятно, а не чтобы было готово к употреблению. К тому же я не вижу смысла обеспечивать возможность одновременной работы инстансов класса созданных на разных типах чисел.
1 |
0 / 0 / 0 Регистрация: 15.01.2016 Сообщений: 17 |
|
13.01.2017, 23:22 [ТС] |
19 |
Самый простой вариант для сложения инстансов разных типов сначала спросила, потом сделала то о чем спросила Добавлено через 8 минут
я написал чтобы было понятно, а не чтобы было готово к употреблению. Я это поняла, просто что-то запустила.. и из-за ошибок забыла, что вообще переделать хотела..
0 |
IGPIGP Комп_Оратор) 8776 / 4515 / 608 Регистрация: 04.12.2011 Сообщений: 13,468 Записей в блоге: 16 |
||||
16.01.2017, 13:32 |
20 |
|||
AlisaChoi, там невнимательно я прочёл и понаписал. Ссылку возвращают операторы +=, -+, *=, /=, инкремент, декремент, присваивание…
Простите за то, что запутал.
1 |
ostream &operator<<(ostream &os, const PT &p) {
os << "(" << p.x << "," << p.y << ")";
}
как исправить код?
задан 14 ноя 2017 в 12:31
1
1 ответ
ostream& operator<<(ostream& os, const PT& p)
{
os << "(" << p.x << "," << p.y << ")";
return os;
}
ответ дан 14 ноя 2017 в 13:26
JensJens
3,3652 золотых знака19 серебряных знаков43 бронзовых знака
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Warning (level 1) C4716 |
Compiler Warning (level 1) C4716 |
11/04/2016 |
C4716 |
C4716 |
d95ecfe5-870f-461f-a746-7913af98414b |
‘function’ must return a value
The given function did not return a value.
Only functions with a return type of void can use the return command without an accompanying return value.
An undefined value will be returned when this function is called.
This warning is automatically promoted to an error. If you wish to modify this behavior, use #pragma warning.
The following sample generates C4716:
// C4716.cpp // compile with: /c /W1 // C4716 expected #pragma warning(default:4716) int test() { // uncomment the following line to resolve // return 0; }
My problem is quite simple, yet I fail to understand the cause of it and no similiar posting has turned up even after extensive research so here it is:
I have the following operator overload:
template <class T, size_t size>
inline Vector<T, size> operator + (Vector<T, size> &a, Vector<T, size> &b) {
Vector<T, size> result;
for (auto i = 0; i < size; ++i) {
result[i] = a[i] + b[i];
}
return result;
}
Obiously there’s only a single code path, and this path also returns a value, but compiling under Visual Studio 2013, I get an error C4716, stating that the function instantiated by the compiler ‘must return a value’. I get this error for all instantiations I’ve tried so far. I also get this error for every other operator overload in the same header, all of which are structured similarly to the snippet above.
Am I missing something obvious here?
EDIT: This is the templated vector class definition:
template <class T, size_t size>
struct Vector {
explicit Vector(T value = static_cast<T>(0)) {
for (auto i = 0; i < size; ++i) {
_data[i] = value;
}
}
explicit Vector(const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
}
explicit Vector(T values[size]) {
for (auto i = 0; i < size; ++i) {
_data[i] = values[i];
}
}
T & operator = (const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
return *this;
}
T & operator [] (size_t index) {
return _data[index];
}
T _data[size];
};
My problem is quite simple, yet I fail to understand the cause of it and no similiar posting has turned up even after extensive research so here it is:
I have the following operator overload:
template <class T, size_t size>
inline Vector<T, size> operator + (Vector<T, size> &a, Vector<T, size> &b) {
Vector<T, size> result;
for (auto i = 0; i < size; ++i) {
result[i] = a[i] + b[i];
}
return result;
}
Obiously there’s only a single code path, and this path also returns a value, but compiling under Visual Studio 2013, I get an error C4716, stating that the function instantiated by the compiler ‘must return a value’. I get this error for all instantiations I’ve tried so far. I also get this error for every other operator overload in the same header, all of which are structured similarly to the snippet above.
Am I missing something obvious here?
EDIT: This is the templated vector class definition:
template <class T, size_t size>
struct Vector {
explicit Vector(T value = static_cast<T>(0)) {
for (auto i = 0; i < size; ++i) {
_data[i] = value;
}
}
explicit Vector(const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
}
explicit Vector(T values[size]) {
for (auto i = 0; i < size; ++i) {
_data[i] = values[i];
}
}
T & operator = (const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
return *this;
}
T & operator [] (size_t index) {
return _data[index];
}
T _data[size];
};
Содержание
- Error c4716 visual studio
- Answered by:
- Question
- Answers
- All replies
- Error c4716 visual studio
- Answered by:
- Question
- Answers
- All replies
- Error c4716 visual studio
- Answered by:
- Question
- Answers
- All replies
- Русские Блоги
- Ошибка C4716 должна вернуть обработку значений
- вопрос
- решать
- Интеллектуальная рекомендация
- Реализация оценки приложения iOS
- JS функциональное программирование (е)
- PWN_JarvisOJ_Level1
- Установка и развертывание Kubernetes
- На стороне многопроцессорного сервера — (2) *
- Ошибки и предупреждения режима сборки проекта (PRJxxxx)
Error c4716 visual studio
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
this code gives me errors .
Answers
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
Dear Raheel marwat,
Could you please tell me whether you have resolve your issue by Selvam’s suggestion. I will mark his reply as the answer. If his suggesion cannot help you, please feel free and unmark the reply. Thanks for your understanding. If anything is unclear, please feel free and let me know.
Rob Pan [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Источник
Error c4716 visual studio
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
this code gives me errors .
Answers
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
Dear Raheel marwat,
Could you please tell me whether you have resolve your issue by Selvam’s suggestion. I will mark his reply as the answer. If his suggesion cannot help you, please feel free and unmark the reply. Thanks for your understanding. If anything is unclear, please feel free and let me know.
Rob Pan [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Источник
Error c4716 visual studio
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
this code gives me errors .
Answers
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
You have to include the pthreadVC1.lib file in in you your linker input.
Project->Properties-> Configuration Properties->Linker->Input->Additional Dependencies->»
Thanks and Regards Selvam http://www15.brinkster.com/selvamselvam/
Dear Raheel marwat,
Could you please tell me whether you have resolve your issue by Selvam’s suggestion. I will mark his reply as the answer. If his suggesion cannot help you, please feel free and unmark the reply. Thanks for your understanding. If anything is unclear, please feel free and let me know.
Rob Pan [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Источник
Русские Блоги
Ошибка C4716 должна вернуть обработку значений
вопрос
Сообщите о следующих ошибках, как решить его на некоторое время. Запись здесь.
Ошибка C4716: «TapamaInterface :: geteventValue»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: geteventValue»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: geteventValue»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: geteventValue»: должен вернуть значение
Ошибка C4716: «Tapamainterface :: get sequencevalue»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: getDictionaryOperator»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: getDictionaryOperator»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: getDictionaryOperator»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: getDictionaryOperator»: должен вернуть значение
Ошибка C4716: «TapamaInterface :: geteventValue»: должен вернуть значение
Исходный код заключается в следующем, такого кода не нужно устанавливать возвращаемое значение
решать
Установите атрибуты проекта «Отключить конкретное предупреждение» 4716 в высоких уровнях в C/C ++, решить.
END
Интеллектуальная рекомендация
Реализация оценки приложения iOS
Есть два способа получить оценку приложения: перейти в App Store для оценки и оценка в приложении. 1. Перейдите в App Store, чтобы оценить ps: appid можно запросить в iTunes Connect 2. Встроенная оцен.
JS функциональное программирование (е)
Давайте рассмотрим простой пример, чтобы проиллюстрировать, как используется Reduce. Первый параметр Reduce — это то, что мы принимаем массив arrayOfNums, а второй параметр — функцию. Эта функция прин.
PWN_JarvisOJ_Level1
Nc первый Затем мы смотрим на декомпиляцию ida Перед «Hello, World! N» есть уязвимая_функция, проверьте эту функцию после ввода Видно, что только что появившийся странный адрес является пе.
Установка и развертывание Kubernetes
На самом деле, я опубликовал статью в этом разделе давным -давно, но она не достаточно подробно, и уровень не является ясным. Когда я развернулся сегодня, я увидел его достаточно (хотя это было успешн.
На стороне многопроцессорного сервера — (2) *
Обработка сигнала Родительский процесс часто очень занят, поэтому вы не можете просто вызвать функцию waitpid, чтобы дождаться завершения дочернего процесса. Затем обсудите решение. Обратитесь .
Источник
Ошибки и предупреждения режима сборки проекта (PRJxxxx)
Этот раздел содержит ссылку на ошибки, созданные средствами сборки Project. Ошибки и предупреждения сборки проекта имеют форму PRJxxxx, где xxxx — четырехзначное число.
Компиляторы и средства сборки Visual Studio могут сообщать о различных типах ошибок и предупреждений. После обнаружения ошибки или предупреждения средства сборки могут делать предположения о намерении кода и пытаться продолжить работу, чтобы можно было сообщать о дополнительных проблемах одновременно. Если средства делают неверное предположение, последующие ошибки или предупреждения не могут применяться к проекту. При устранении проблем в проекте всегда начинайте с первой зарегистрированной ошибки (или предупреждения) и выполняйте повторную сборку как можно чаще. Одно исправление может привести к возникновению многих последующих ошибок.
Чтобы получить справку о конкретном диагностическом сообщении в Visual Studio, выберите его в окне вывода и нажмите клавишу F1 . Visual Studio открывает страницу документации для этой ошибки, если она существует. Вы также можете использовать средство поиска в верхней части страницы, чтобы найти статьи о конкретных ошибках или предупреждениях. Кроме того, просмотрите список ошибок и предупреждений по инструменту и введите оглавление на этой странице.
Не все ошибки или предупреждения Visual Studio описаны. Во многих случаях диагностическое сообщение предоставляет все доступные сведения. Если вы приземлились на этой странице при использовании F1 и считаете, что сообщение об ошибке или предупреждении требует дополнительного объяснения, сообщите нам об этом. Кнопки обратной связи на этой странице можно использовать для создания проблемы с документацией на сайте GitHub. Если вы считаете, что ошибка или предупреждение неправы или обнаружена другая проблема с набором инструментов, сообщите о проблеме с продуктом на сайте Сообщество разработчиков. Вы также можете отправить отзыв и ввести ошибки в интегрированной среде разработки. В Visual Studio перейдите в строку меню и выберите «Отправить > отзыв справки>» или отправьте предложение с помощью отправки > отзывов > справки.
Вы можете найти дополнительную помощь по ошибкам и предупреждениям на форумах Microsoft Learn Q&A . Или найдите номер ошибки или предупреждения на сайте Сообщество разработчиков Visual Studio C++. Вы также можете выполнить поиск решений в Stack Overflow .
Ссылки на дополнительные справочные материалы и ресурсы сообщества см. в справке и сообществе Visual C++.
Источник
Моя проблема довольно проста, но я не понимаю причины ее возникновения, и даже после обширных исследований не появилось ни одного подобного сообщения, поэтому вот оно:
У меня есть следующая перегрузка оператора:
template <class T, size_t size>
inline Vector<T, size> operator + (Vector<T, size> &a, Vector<T, size> &b) {
Vector<T, size> result;
for (auto i = 0; i < size; ++i) {
result[i] = a[i] + b[i];
}
return result;
}
Очевидно, что существует только один путь к коду, и этот путь также возвращает значение, но при компиляции в Visual Studio 2013 я получаю ошибку C4716, утверждающую, что функция, созданная компилятором, «должна возвращать значение». Я получаю эту ошибку для всех экземпляров, которые я пробовал до сих пор. Я также получаю эту ошибку для всех других операторов перегрузки в том же заголовке, все из которых структурированы аналогично приведенному выше фрагменту.
Я что-то упускаю здесь очевидное?
РЕДАКТИРОВАТЬ: Это шаблонное определение векторного класса:
template <class T, size_t size>
struct Vector {
explicit Vector(T value = static_cast<T>(0)) {
for (auto i = 0; i < size; ++i) {
_data[i] = value;
}
}
explicit Vector(const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
}
explicit Vector(T values[size]) {
for (auto i = 0; i < size; ++i) {
_data[i] = values[i];
}
}
T & operator = (const Vector &other) {
for (auto i = 0; i < size; ++i) {
_data[i] = other._data[i];
}
return *this;
}
T & operator [] (size_t index) {
return _data[index];
}
T _data[size];
};
0
Решение
Проблема была решена для меня, сделав конструктор копирования Vector неявным.
Чтобы описать, как я пришел к такому выводу, я пошел и специализировал операторную функцию для Vector:
template <>
inline Vector<int, 1> operator + (Vector<int, 1> &a, Vector<int, 1> &b) {
Vector<int, 1> result;
return result;
}
В Visual Studio возникла ошибка, в которой говорится, что для возвращаемого значения не существует подходящего конструктора копирования, что было устранено путем удаления явного ключевого слова из конструктора копирования.
Это было бы очевидно для меня, если бы я правильно понял, как работают явные конструкторы копирования.
0
Другие решения
Recommended Answers
1. About C4716: didn’t you know that
double F_Ite()
function must return double type value? And where isreturn anything-of-double_type
in the function body? It’s your code, you have wrotedouble F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source[/code]
It’s impossible …
Jump to Post
Why dont you use an array of pointers and return the array of pointers.
Jump to Post
As the other guys have suggested, there are several ways around the problem.
The error you’re getting is because your F_Ite() function does not return a value.A function can only return one value, the only way of returning several values would be to either create all of the …
Jump to Post
All 9 Replies
ArkM
1,090
Postaholic
13 Years Ago
1. About C4716: didn’t you know that double F_Ite()
function must return double type value? And where is return anything-of-double_type
in the function body? It’s your code, you have wrote double F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source
[/code]
It’s impossible to cope with this unformatted nightmare!
3. There are two common ways to «return» several values:
3.1 Declare several function parameters (pointers or references to targets).
3.2 Declare a proper struct or class compound type then fill the object of this type and return it as a function value.
13 Years Ago
Why dont you use an array of pointers and return the array of pointers.
13 Years Ago
#include<iostream>
#include<cmath>
#include<algorithm>
void showdata(void);
double R_Fibo();
double F_Ite();
//double F_Ite(double,double,double,double,double,double);
// never ever declare global data in C++
//Globally Data_type Declaration & Initialization :
double z=0.0001;
double NR=0.01;
int NI=11;
double RF;
int main(int argc, char* argv[])
{
std::cout <<"nThe Function is ' F(x)=e^(-x)+x^2 '";
std::cout <<"n";
int numElement =20;
double *a,*b,*c,*d,*Fc,*Fd,I;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
//User Specify The Interval :
std::cout << "nGive The Initian Point :" <<"na1 =";
std::cin >> a[1];
std::cout << "nGive The Final Point :" <<"nb1 =";
std::cin >> b[1];
//Find Distance Between The Starting Interval :
I=(b[1]-a[1]);
std::cout << "nInterval Reduction At The Initial Iteration :"<< "nI(1) = " << I <<"n";
//Here The Beginnins Of Iteration Technique
//We Introduce Two Another Points For Getting Two New Interval Of Uncertainty
//First Point 'c1' And Second Point 'd1' :
c[1]=b[1]-(R_Fibo()*I);
std::cout << "nPlaced A Point c1 Within The Initial Interval :"<< c[1];
d[1]=a[1]+(R_Fibo()*I);
std::cout <<"nPlaced Another Point d1 Within The Initial Interval :"<<d[1];
std::cout <<"n";
std::cout <<"n";
//Showing The Starting Reduction :
//----------------
//----------------
std::cout <<"At The First Iteration :n";
std::cout <<"The Value Of a1=" << a[1] << "n";
std::cout <<"The Value Of b1=" << b[1] << "n";
std::cout <<"The Value Of c1=" << c[1] << "n";
std::cout <<"The Value Of d1=" << d[1] ;
//--------------------
//Function 'Fc1' at point 'c1' And Function 'Fd1' at point 'd1':
// write a function which takes one argument and returns the value. use it here instead of explicit coding.
Fc[1]=(exp(-c[1]))+(c[1]*c[1]);
std::cout << "nAt c1 The Function Value Fc1=" << Fc[1];
//std::cout <<"n";
Fd[1]=(exp(-d[1]))+(d[1]*d[1]);
std::cout << "nAt d1 The Function Value Fd1=" << Fd[1];
std::cout <<"n";
std::cout <<"n";
//---------------------
//---------------------
double In=b[NI]-a[NI];
std::cout <<"nThe Interval Reduction At The Final Iteration :" <<"nI(n)= " << In;
std::cout<<"n";
std::cout << std::endl;
system("pause");
//return 0;
}
void showdata(void)
{
//For Accuracy Exactness Need A Small Pertubation At The Final Interval
std::cout <<"nFor Accuracy At The Final Interval, Taken The Small Perturbation z :";
std::cout <<"nTaken z = 0.0001" << "n";
//Give The Prescribe Interval Reduction :
std::cout <<"nNeeded The Prescribe Interval Reduction :" <<"nNR = 0.01 units";
std::cout <<"n";
//Calculate The Number Of Iteration From The Given Interval Reduction :
//By Fibonacci Series
std::cout <<"nAccording To The Interval Reduction";
std::cout <<"nThe Requring Number Of Iteration :" << "nNI = 11 times";
std::cout <<"n";
std::cout <<"n";
std::cout <<"nBefore The Start Of Interval Reduction";
std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = 0.618056";
std::cout <<"n";
}
double R_Fibo()
{
//Ratio of two successive terms of Fibonacci Sequence is obtained using Binet's Formula
//Function (F(m-1)/Fm) Defination :
double n1=1-(sqrt((double)5));
double n2=1+(sqrt((double)5));
double s=(n1/n2);
//cout << "nsThe Value Of s = " << s <<"n";
double s1=(sqrt((double)5)-1)/2;
//cout << "nThe Value Of s1 = " << s1 <<"n";
double RF=s1*((1-pow(s,NI))/(1-pow(s,(NI+1))));
//std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = " << RF <<"n";
//std::cout << RF;
return RF;
}
double F_Ite()
{ //F_Ite Function Start
//Locally Data_type Declaration And Initialization :
int numElement =20;
double *a,*b,*c,*d,*Fc,*Fd;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop under F_Ite() Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //F_Ite Function Close
this is my total program.so how to return several values.
13 Years Ago
Why dont you use an array of pointers and return the array of pointers.
Will u pls help me how to do this?
JasonHippy
724
Practically a Master Poster
13 Years Ago
As the other guys have suggested, there are several ways around the problem.
The error you’re getting is because your F_Ite() function does not return a value.
A function can only return one value, the only way of returning several values would be to either create all of the variables you want returned outside of your function and pass them into your function as pointers or references, or pass them as an array of pointers.
You could then change the return type of the function to void as the function will manipulate the contents of the pointers, so it won’t need to return anything.
Or you could get your function to return an array of pointers.
I’m not sure how au-fait you are with the idea of pointers and arrays, so for now I’ll go with the idea of creating the values outside of the function and passing them individually as pointers.
Here’s what the code would look like:
#include<iostream>
#include<cmath>
// pass values into your function
void F_Ite(double *a, double *b, double *c, double *d, double *Fc, double *Fd)
{ //Main Function Start
// you could initialise your variables here, or outside of the function.
// I've gone for the latter, but whatever floats your boat!
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //Main Function Close
int main()
{
// declare your pointers outside of your function and pass them as parameters to F_Ite
double *a,*b,*c,*d,*Fc,*Fd;
// you could optionally initialise them before passing them to your function
int numElement =20;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
// now call the function
F_Ite(a,b,c,d,Fc,Fd);
// Now you can cout your values, or do whatever with them
// don't forget to delete them when you're done.
// wherever you create something with 'new' you should
// always call 'delete' when finished!
return 0;
}
NOTE: The bulk of the above is your code, just rejigged a little.
DISCLAIMER: I haven’t compiled or tested this, but it should be more or less correct!
Cheers for now,
Jas.
13 Years Ago
1. About C4716: didn’t you know that
double F_Ite()
function must return double type value? And where isreturn anything-of-double_type
in the function body? It’s your code, you have wrotedouble F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source[/code]
It’s impossible to cope with this unformatted nightmare!
3. There are two common ways to «return» several values:
3.1 Declare several function parameters (pointers or references to targets).
3.2 Declare a proper struct or class compound type then fill the object of this type and return it as a function value.
Declare several function parameters (pointers or references to targets). I have tried this but unable to get success.I have post my total code just pls check it out & pls suggest me some useful concept.
13 Years Ago
Firstly Please USE Code tags, as it is very hard to understand the post that you have posted.
I personally feel that for you the best way to return your doubles is with a struct.
for example
struct Values{ //Creates a new datatype named values
double* a, *b;//SO on.
}
Values func1()// function named func1 returning type Values
{
double *s, *z;
/*Do something with s and z*/
Values a1;// Now we made a variable named a1 of type value
a1.a=&s; //We know that Values have a member a;
a1.b=&z; //And also b, We now make them point to the local doubles
return a1; //Return type of values
}
int main()
Values f1=func1();
}
then now f1.a and f1.b will point to the doubles.
THough remember that pointers to local variables is undefined and only the variables initialised with new are returned back.
DO not forget to use the delete []
later.
JasonHippy
724
Practically a Master Poster
13 Years Ago
I personally feel that for you the best way to return your doubles is with a struct.
I second that motion!
That would be preferable to the method I put forward.
I just wasn’t sure how familiar the OP was with structs, pointers and arrays. So I went with the simplest example passing each value separately….
Although looking my post now, why I posted the entire body of the function instead of just posting a more compact example is beyond me! heh heh
Good solution Sky!
13 Years Ago
hi friends,right now I am facing this type of problem.Will anyone please help me out.please as I am New inC++ & after tried not getting.
Thanks
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std; // you should not use this statement.
void F_Ite(double,double,double,double,double,double);
// never ever declare global data in C++
//Globally Data_type Declaration & Initialization :
double z=0.0001;
double NR=0.01;
int NI=11;
double RF;
int main(int argc, char* argv[]) // put the othe arguments for main (int argc, char* argv[])
{
//Result Of A Fibonacci_Search Algorithm Operation On A Given Function :
std::cout <<"nThe Function is ' F(x)=e^(-x)+x^2 '";
std::cout <<"n";
// declare your pointers outside of your function and pass them as parameters to F_Ite
double *a,*b,*c,*d,*Fc,*Fd,I;
// you could optionally initialise them before passing them to your function
int numElement =20;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
// now call the function
F_Ite(a,b,c,d,Fc,Fd);
// Now you can cout your values, or do whatever with them
// don't forget to delete them when you're done.
// wherever you create something with 'new' you should
// always call 'delete' when finished!
//User Specify The Interval :
std::cout << "nGive The Initian Point :" <<"na1 =";
std::cin >> a[1];
std::cout << "nGive The Final Point :" <<"nb1 =";
std::cin >> b[1];
//Find Distance Between The Starting Interval :
I=(b[1]-a[1]);
std::cout << "nInterval Reduction At The Initial Iteration :"<< "nI(1) = " << I <<"n";
//For Accuracy Exactness Need A Small Pertubation At The Final Interval
std::cout <<"nFor Accuracy At The Final Interval, Taken The Small Perturbation z :";
std::cout <<"nTaken z = 0.0001" << "n";
//Give The Prescribe Interval Reduction :
std::cout <<"nNeeded The Prescribe Interval Reduction :" <<"nNR = 0.01 units";
std::cout <<"n";
//Calculate The Number Of Iteration From The Given Interval Reduction :
//By Fibonacci Series
std::cout <<"nAccording To The Interval Reduction";
std::cout <<"nThe Requring Number Of Iteration :" << "nNI = 11 times";
std::cout <<"n";
std::cout <<"n";
system("pause"); // this is a platform specific call. do not use this.
//To Calculate The Ratio of two consecutive Fibo_Num (F(m-1)/Fm) :
//Function (F(m-1)/Fm) Declaration :
double R_Fibo();
std::cout <<"nBefore The Start Of Interval Reduction";
std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = 0.618056";
std::cout <<"n";
//Here The Beginnins Of Iteration Technique
//We Introduce Two Another Points For Getting Two New Interval Of Uncertainty
//First Point 'c1' And Second Point 'd1' :
c[1]=b[1]-(R_Fibo()*I);
std::cout << "nPlaced A Point c1 Within The Initial Interval :"<< c[1];
d[1]=a[1]+(R_Fibo()*I);
std::cout <<"nPlaced Another Point d1 Within The Initial Interval :"<<d[1];
std::cout <<"n";
std::cout <<"n";
//Showing The Starting Reduction :
//----------------
//----------------
std::cout <<"At The First Iteration :n";
std::cout <<"The Value Of a1=" << a[1] << "n";
std::cout <<"The Value Of b1=" << b[1] << "n";
std::cout <<"The Value Of c1=" << c[1] << "n";
std::cout <<"The Value Of d1=" << d[1] ;
//Function 'Fc1' at point 'c1' And Function 'Fd1' at point 'd1':
//--------------------
// write a function which takes one argument and returns the value. use it here instead of explicit coding.
Fc[1]=(exp(-c[1]))+(c[1]*c[1]);
std::cout << "nAt c1 The Function Value Fc1=" << Fc[1];
//std::cout <<"n";
Fd[1]=(exp(-d[1]))+(d[1]*d[1]);
std::cout << "nAt d1 The Function Value Fd1=" << Fd[1];
std::cout <<"n";
std::cout <<"n";
//---------------------
//---------------------
//system("pause");
// this must be defined outside of main and called here explicitly.
double In=b[NI]-a[NI];
std::cout <<"nThe Interval Reduction At The Final Iteration :" <<"nI(n)= " << In;
std::cout<<"n";
delete [] a;
delete [] b;
delete [] c;
delete [] d;
delete [] Fc;
delete [] Fd;
std::cout << std::endl;
system("pause");
//return 0;
}
//Ratio of two successive terms of Fibonacci Sequence is obtained using Binet's Formula
//Function (F(m-1)/Fm) Defination :
double R_Fibo()
{
double n1=1-(sqrt((double)5));
double n2=1+(sqrt((double)5));
double s=(n1/n2);
//cout << "nsThe Value Of s = " << s <<"n";
double s1=(sqrt((double)5)-1)/2;
//cout << "nThe Value Of s1 = " << s1 <<"n";
double RF=s1*((1-pow(s,NI))/(1-pow(s,(NI+1))));
//std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = " << RF <<"n";
//std::cout << RF;
return RF;
}
// pass values into F_Ite() function
void F_Ite(double *a, double *b, double *c, double *d, double *Fc, double *Fd)
{ //F_Ite Function Start
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //F_Ite Function Close
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Recommended Answers
1. About C4716: didn’t you know that
double F_Ite()
function must return double type value? And where isreturn anything-of-double_type
in the function body? It’s your code, you have wrotedouble F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source[/code]
It’s impossible …
Jump to Post
Why dont you use an array of pointers and return the array of pointers.
Jump to Post
As the other guys have suggested, there are several ways around the problem.
The error you’re getting is because your F_Ite() function does not return a value.A function can only return one value, the only way of returning several values would be to either create all of the …
Jump to Post
All 9 Replies
ArkM
1,090
Postaholic
13 Years Ago
1. About C4716: didn’t you know that double F_Ite()
function must return double type value? And where is return anything-of-double_type
in the function body? It’s your code, you have wrote double F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source
[/code]
It’s impossible to cope with this unformatted nightmare!
3. There are two common ways to «return» several values:
3.1 Declare several function parameters (pointers or references to targets).
3.2 Declare a proper struct or class compound type then fill the object of this type and return it as a function value.
13 Years Ago
Why dont you use an array of pointers and return the array of pointers.
13 Years Ago
#include<iostream>
#include<cmath>
#include<algorithm>
void showdata(void);
double R_Fibo();
double F_Ite();
//double F_Ite(double,double,double,double,double,double);
// never ever declare global data in C++
//Globally Data_type Declaration & Initialization :
double z=0.0001;
double NR=0.01;
int NI=11;
double RF;
int main(int argc, char* argv[])
{
std::cout <<"nThe Function is ' F(x)=e^(-x)+x^2 '";
std::cout <<"n";
int numElement =20;
double *a,*b,*c,*d,*Fc,*Fd,I;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
//User Specify The Interval :
std::cout << "nGive The Initian Point :" <<"na1 =";
std::cin >> a[1];
std::cout << "nGive The Final Point :" <<"nb1 =";
std::cin >> b[1];
//Find Distance Between The Starting Interval :
I=(b[1]-a[1]);
std::cout << "nInterval Reduction At The Initial Iteration :"<< "nI(1) = " << I <<"n";
//Here The Beginnins Of Iteration Technique
//We Introduce Two Another Points For Getting Two New Interval Of Uncertainty
//First Point 'c1' And Second Point 'd1' :
c[1]=b[1]-(R_Fibo()*I);
std::cout << "nPlaced A Point c1 Within The Initial Interval :"<< c[1];
d[1]=a[1]+(R_Fibo()*I);
std::cout <<"nPlaced Another Point d1 Within The Initial Interval :"<<d[1];
std::cout <<"n";
std::cout <<"n";
//Showing The Starting Reduction :
//----------------
//----------------
std::cout <<"At The First Iteration :n";
std::cout <<"The Value Of a1=" << a[1] << "n";
std::cout <<"The Value Of b1=" << b[1] << "n";
std::cout <<"The Value Of c1=" << c[1] << "n";
std::cout <<"The Value Of d1=" << d[1] ;
//--------------------
//Function 'Fc1' at point 'c1' And Function 'Fd1' at point 'd1':
// write a function which takes one argument and returns the value. use it here instead of explicit coding.
Fc[1]=(exp(-c[1]))+(c[1]*c[1]);
std::cout << "nAt c1 The Function Value Fc1=" << Fc[1];
//std::cout <<"n";
Fd[1]=(exp(-d[1]))+(d[1]*d[1]);
std::cout << "nAt d1 The Function Value Fd1=" << Fd[1];
std::cout <<"n";
std::cout <<"n";
//---------------------
//---------------------
double In=b[NI]-a[NI];
std::cout <<"nThe Interval Reduction At The Final Iteration :" <<"nI(n)= " << In;
std::cout<<"n";
std::cout << std::endl;
system("pause");
//return 0;
}
void showdata(void)
{
//For Accuracy Exactness Need A Small Pertubation At The Final Interval
std::cout <<"nFor Accuracy At The Final Interval, Taken The Small Perturbation z :";
std::cout <<"nTaken z = 0.0001" << "n";
//Give The Prescribe Interval Reduction :
std::cout <<"nNeeded The Prescribe Interval Reduction :" <<"nNR = 0.01 units";
std::cout <<"n";
//Calculate The Number Of Iteration From The Given Interval Reduction :
//By Fibonacci Series
std::cout <<"nAccording To The Interval Reduction";
std::cout <<"nThe Requring Number Of Iteration :" << "nNI = 11 times";
std::cout <<"n";
std::cout <<"n";
std::cout <<"nBefore The Start Of Interval Reduction";
std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = 0.618056";
std::cout <<"n";
}
double R_Fibo()
{
//Ratio of two successive terms of Fibonacci Sequence is obtained using Binet's Formula
//Function (F(m-1)/Fm) Defination :
double n1=1-(sqrt((double)5));
double n2=1+(sqrt((double)5));
double s=(n1/n2);
//cout << "nsThe Value Of s = " << s <<"n";
double s1=(sqrt((double)5)-1)/2;
//cout << "nThe Value Of s1 = " << s1 <<"n";
double RF=s1*((1-pow(s,NI))/(1-pow(s,(NI+1))));
//std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = " << RF <<"n";
//std::cout << RF;
return RF;
}
double F_Ite()
{ //F_Ite Function Start
//Locally Data_type Declaration And Initialization :
int numElement =20;
double *a,*b,*c,*d,*Fc,*Fd;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop under F_Ite() Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //F_Ite Function Close
this is my total program.so how to return several values.
13 Years Ago
Why dont you use an array of pointers and return the array of pointers.
Will u pls help me how to do this?
JasonHippy
724
Practically a Master Poster
13 Years Ago
As the other guys have suggested, there are several ways around the problem.
The error you’re getting is because your F_Ite() function does not return a value.
A function can only return one value, the only way of returning several values would be to either create all of the variables you want returned outside of your function and pass them into your function as pointers or references, or pass them as an array of pointers.
You could then change the return type of the function to void as the function will manipulate the contents of the pointers, so it won’t need to return anything.
Or you could get your function to return an array of pointers.
I’m not sure how au-fait you are with the idea of pointers and arrays, so for now I’ll go with the idea of creating the values outside of the function and passing them individually as pointers.
Here’s what the code would look like:
#include<iostream>
#include<cmath>
// pass values into your function
void F_Ite(double *a, double *b, double *c, double *d, double *Fc, double *Fd)
{ //Main Function Start
// you could initialise your variables here, or outside of the function.
// I've gone for the latter, but whatever floats your boat!
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //Main Function Close
int main()
{
// declare your pointers outside of your function and pass them as parameters to F_Ite
double *a,*b,*c,*d,*Fc,*Fd;
// you could optionally initialise them before passing them to your function
int numElement =20;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
// now call the function
F_Ite(a,b,c,d,Fc,Fd);
// Now you can cout your values, or do whatever with them
// don't forget to delete them when you're done.
// wherever you create something with 'new' you should
// always call 'delete' when finished!
return 0;
}
NOTE: The bulk of the above is your code, just rejigged a little.
DISCLAIMER: I haven’t compiled or tested this, but it should be more or less correct!
Cheers for now,
Jas.
13 Years Ago
1. About C4716: didn’t you know that
double F_Ite()
function must return double type value? And where isreturn anything-of-double_type
in the function body? It’s your code, you have wrotedouble F_Ite()
…
2. Use code tag with the language specifier (see this forum announcements):
[code=cplusplus]
source[/code]
It’s impossible to cope with this unformatted nightmare!
3. There are two common ways to «return» several values:
3.1 Declare several function parameters (pointers or references to targets).
3.2 Declare a proper struct or class compound type then fill the object of this type and return it as a function value.
Declare several function parameters (pointers or references to targets). I have tried this but unable to get success.I have post my total code just pls check it out & pls suggest me some useful concept.
13 Years Ago
Firstly Please USE Code tags, as it is very hard to understand the post that you have posted.
I personally feel that for you the best way to return your doubles is with a struct.
for example
struct Values{ //Creates a new datatype named values
double* a, *b;//SO on.
}
Values func1()// function named func1 returning type Values
{
double *s, *z;
/*Do something with s and z*/
Values a1;// Now we made a variable named a1 of type value
a1.a=&s; //We know that Values have a member a;
a1.b=&z; //And also b, We now make them point to the local doubles
return a1; //Return type of values
}
int main()
Values f1=func1();
}
then now f1.a and f1.b will point to the doubles.
THough remember that pointers to local variables is undefined and only the variables initialised with new are returned back.
DO not forget to use the delete []
later.
JasonHippy
724
Practically a Master Poster
13 Years Ago
I personally feel that for you the best way to return your doubles is with a struct.
I second that motion!
That would be preferable to the method I put forward.
I just wasn’t sure how familiar the OP was with structs, pointers and arrays. So I went with the simplest example passing each value separately….
Although looking my post now, why I posted the entire body of the function instead of just posting a more compact example is beyond me! heh heh
Good solution Sky!
13 Years Ago
hi friends,right now I am facing this type of problem.Will anyone please help me out.please as I am New inC++ & after tried not getting.
Thanks
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std; // you should not use this statement.
void F_Ite(double,double,double,double,double,double);
// never ever declare global data in C++
//Globally Data_type Declaration & Initialization :
double z=0.0001;
double NR=0.01;
int NI=11;
double RF;
int main(int argc, char* argv[]) // put the othe arguments for main (int argc, char* argv[])
{
//Result Of A Fibonacci_Search Algorithm Operation On A Given Function :
std::cout <<"nThe Function is ' F(x)=e^(-x)+x^2 '";
std::cout <<"n";
// declare your pointers outside of your function and pass them as parameters to F_Ite
double *a,*b,*c,*d,*Fc,*Fd,I;
// you could optionally initialise them before passing them to your function
int numElement =20;
a = new double[numElement];
b = new double[numElement];
c = new double[numElement];
d = new double[numElement];
Fc= new double[numElement];
Fd= new double[numElement];
// now call the function
F_Ite(a,b,c,d,Fc,Fd);
// Now you can cout your values, or do whatever with them
// don't forget to delete them when you're done.
// wherever you create something with 'new' you should
// always call 'delete' when finished!
//User Specify The Interval :
std::cout << "nGive The Initian Point :" <<"na1 =";
std::cin >> a[1];
std::cout << "nGive The Final Point :" <<"nb1 =";
std::cin >> b[1];
//Find Distance Between The Starting Interval :
I=(b[1]-a[1]);
std::cout << "nInterval Reduction At The Initial Iteration :"<< "nI(1) = " << I <<"n";
//For Accuracy Exactness Need A Small Pertubation At The Final Interval
std::cout <<"nFor Accuracy At The Final Interval, Taken The Small Perturbation z :";
std::cout <<"nTaken z = 0.0001" << "n";
//Give The Prescribe Interval Reduction :
std::cout <<"nNeeded The Prescribe Interval Reduction :" <<"nNR = 0.01 units";
std::cout <<"n";
//Calculate The Number Of Iteration From The Given Interval Reduction :
//By Fibonacci Series
std::cout <<"nAccording To The Interval Reduction";
std::cout <<"nThe Requring Number Of Iteration :" << "nNI = 11 times";
std::cout <<"n";
std::cout <<"n";
system("pause"); // this is a platform specific call. do not use this.
//To Calculate The Ratio of two consecutive Fibo_Num (F(m-1)/Fm) :
//Function (F(m-1)/Fm) Declaration :
double R_Fibo();
std::cout <<"nBefore The Start Of Interval Reduction";
std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = 0.618056";
std::cout <<"n";
//Here The Beginnins Of Iteration Technique
//We Introduce Two Another Points For Getting Two New Interval Of Uncertainty
//First Point 'c1' And Second Point 'd1' :
c[1]=b[1]-(R_Fibo()*I);
std::cout << "nPlaced A Point c1 Within The Initial Interval :"<< c[1];
d[1]=a[1]+(R_Fibo()*I);
std::cout <<"nPlaced Another Point d1 Within The Initial Interval :"<<d[1];
std::cout <<"n";
std::cout <<"n";
//Showing The Starting Reduction :
//----------------
//----------------
std::cout <<"At The First Iteration :n";
std::cout <<"The Value Of a1=" << a[1] << "n";
std::cout <<"The Value Of b1=" << b[1] << "n";
std::cout <<"The Value Of c1=" << c[1] << "n";
std::cout <<"The Value Of d1=" << d[1] ;
//Function 'Fc1' at point 'c1' And Function 'Fd1' at point 'd1':
//--------------------
// write a function which takes one argument and returns the value. use it here instead of explicit coding.
Fc[1]=(exp(-c[1]))+(c[1]*c[1]);
std::cout << "nAt c1 The Function Value Fc1=" << Fc[1];
//std::cout <<"n";
Fd[1]=(exp(-d[1]))+(d[1]*d[1]);
std::cout << "nAt d1 The Function Value Fd1=" << Fd[1];
std::cout <<"n";
std::cout <<"n";
//---------------------
//---------------------
//system("pause");
// this must be defined outside of main and called here explicitly.
double In=b[NI]-a[NI];
std::cout <<"nThe Interval Reduction At The Final Iteration :" <<"nI(n)= " << In;
std::cout<<"n";
delete [] a;
delete [] b;
delete [] c;
delete [] d;
delete [] Fc;
delete [] Fd;
std::cout << std::endl;
system("pause");
//return 0;
}
//Ratio of two successive terms of Fibonacci Sequence is obtained using Binet's Formula
//Function (F(m-1)/Fm) Defination :
double R_Fibo()
{
double n1=1-(sqrt((double)5));
double n2=1+(sqrt((double)5));
double s=(n1/n2);
//cout << "nsThe Value Of s = " << s <<"n";
double s1=(sqrt((double)5)-1)/2;
//cout << "nThe Value Of s1 = " << s1 <<"n";
double RF=s1*((1-pow(s,NI))/(1-pow(s,(NI+1))));
//std::cout << "nThe Ratio of two consecutive Fibo_Num :"<<"nRF = " << RF <<"n";
//std::cout << RF;
return RF;
}
// pass values into F_Ite() function
void F_Ite(double *a, double *b, double *c, double *d, double *Fc, double *Fd)
{ //F_Ite Function Start
for(int k=1;k<(NI-1);k++)
{ //Main 'for' Loop Start
std::cout <<"n";
system("pause");
std::cout <<"n";
std::cout <<"At The "<<k+1<<" Iteration :n";
if(Fc[k]<Fd[k])
{ //Outer 'if' Start
a[k+1]=a[k];
cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=d[k];
cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
//c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
//cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
if(k==(NI-1))
{
c[k+1]=c[k+1]+z;
cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
else
{
c[k+1]=b[k+1]-(0.618034*((1-pow(-0.381966,NI-k))/(1-pow(-0.381966,NI-k+1))))*(b[k+1]-a[k+1]);
cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
}
d[k+1]=c[k];
cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
Fc[k+1]=(exp(-c[k+1]))+(c[k+1]*c[k+1]);
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k] << "n";
Fd[k+1]=Fc[k];
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fc[k] << "n";
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
} //Outer 'if' Close
else
{ //Outer 'else' Start
a[k+1]=c[k];
std::cout <<"The Value Of a" << k+1 << "=" << a[k+1] << "n";
b[k+1]=b[k];
std::cout <<"The Value Of b" << k+1 << "=" << b[k+1] << "n";
c[k+1]=d[k];
std::cout <<"The Value Of c" << k+1 << "=" << c[k+1] << "n";
//d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
//std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
if(k==(NI-1))
{
d[k+1]=d[k+1]+z;
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
else
{
d[k+1]=a[k+1]+((0.618034)*((1-pow((-0.381966),(NI-k)))/(1-pow((-0.381966),(NI-k+1)))))*(b[k+1]-a[k+1]);
std::cout <<"The Value Of d" << k+1 << "=" << d[k+1] << "n";
}
Fc[k+1]=Fd[k];
//std::cout <<"The Value Of Fc" << k+1 << "=" << Fd[k] << "n";
std::cout <<"The Value Of Fc" << k+1 << "=" << Fc[k+1] << "n";
Fd[k+1]=(exp(-d[k+1]))+(d[k+1]*d[k+1]);
std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k+1] << "n";
//std::cout <<"The Value Of Fd" << k+1 << "=" << Fd[k] << "n";
} //Outer 'else' Close
} //Main 'for' Loop Close
//Another 'if' Condition Start But Within The 'for' Loop
if(Fc[10]<Fd[10])
{
std::cout <<"n";
std::cout <<"nAt Final Iteration :n";
a[NI]=a[NI-1];
b[NI]=d[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
else
{
a[NI]=c[NI-1];
b[NI]=b[NI-1];
std::cout <<"The Value Of a11 =" << a[NI] << "n";
std::cout <<"The Value Of b11 =" << b[NI] << "n";
}
} //F_Ite Function Close
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.