Error c4716 должна возвращать значение

Ошибка C4716 Complex::operator+=: должна возвращать значение C++ Решение и ответ на вопрос 1897016

AlisaChoi

0 / 0 / 0

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

Сообщений: 17

1

09.01.2017, 22:14. Показов 5956. Ответов 21

Метки нет (Все метки)


У меня vs 2015 c++. Необходимо создать шаблон класса для представления 2-х компонентных комплексных чисел и реализовать перегруженные операторы для всех стандартных операций и т.д.
Код класса complex.h :

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#ifndef __COMPLEX_H__
#define __COMPLEX_H__
 
#include <iostream>
 
template <typename T>
class Complex
{
    template <typename U>
    friend std::istream& operator >> (std::istream&, Complex<U>&);
 
public:
    explicit Complex(const T& re, const T& im);
    Complex(const Complex& other);
 
    Complex& operator=(const Complex& other);
 
    T real() const { return _re; }
    T imaginary() const { return _im; }
 
    Complex conjugate() const { return Complex(_re, -_im); }
 
    Complex& operator+= (const Complex& other);
    Complex& operator-= (const Complex& other);
    Complex& operator*= (const Complex& other);
    Complex& operator/= (const Complex& other);
 
    Complex operator+ (const Complex& other);
    Complex operator- (const Complex& other);
    Complex operator* (const Complex& other);
    Complex operator/ (const Complex& other);
 
private:
    T _re;
    T _im;
};
 
template <typename T>
inline Complex<T>::Complex(const T& re, const T& im)
    : _re(re), _im(im)
{
}
 
template <typename T>
inline Complex<T>::Complex(const Complex& other)
    : _re(other._re), _im(other._im)
{
}
 
template <typename T>
Complex<T>& Complex<T>::operator=(const Complex<T>& other)
{
    if (&other == this)
        return;
 
    _re = other._re;
    _im = other._im;
 
    return *this;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator+= (const Complex<T>& other)
{
    _re += other._re;
    _im += other._im;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator-= (const Complex<T>& other)
{
    _re -= other._re;
    _im -= other._im;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator*= (const Complex<T>& other)
{
    _re = _re * other._re - _im * other._im;
    _im = _im * other._re + _re * other._im;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator/= (const Complex<T>& other)
{
    _re = (_re * other._re - _im * other._im) /
        (other._re * other._re + other._im * other._im);
    _im = (_im * other._re - _re * other._im) /
        (other._re * other._re + other._im * other._im);
}
 
template <typename T>
inline Complex<T> Complex<T>::operator+ (const Complex<T>& other)
{
    return Complex<T>(*this) += other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator- (const Complex<T>& other)
{
    return Complex<T>(*this) -= other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator* (const Complex<T>& other)
{
    return Complex<T>(*this) *= other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator/ (const Complex<T>& other)
{
    return Complex<T>(*this) /= other;
}
 
template <typename T>
std::istream& operator >> (std::istream& in, Complex<T>& c)
{
    return in >> c._re >> c._im;
}
 
template <typename T>
std::ostream& operator<< (std::ostream& out, const Complex<T>& c)
{
    return out << c.real() << " " << c.imaginary();
}
 
#endif //__COMPLEX_H__

При запуске вылетает с ошибками:
1. Ошибка C4716 Complex<int>::operator+=: должна возвращать значение (67)
2. Ошибка C4716 Complex<int>::operator-=: должна возвращать значение (74)
3. Ошибка C4716 Complex<int>::operator*=: должна возвращать значение (81)
4. Ошибка C4716 Complex<int>::operator/=: должна возвращать значение (90)

Понятно, что он хочет return , но чего и зачем непонятно…
Помогите, пожалуйста…

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



0



2431 / 1831 / 404

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

Сообщений: 8,166

09.01.2017, 22:30

2

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

Понятно, что он хочет return , но чего и зачем непонятно…
Помогите, пожалуйста…

Если вам return не нужен, то поставьте void и ничего не возвращайте.



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

10.01.2017, 01:22

3

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

Решение

C++
1
2
3
4
5
6
7
template <typename T>
inline Complex<T>& Complex<T>::operator+= (const Complex<T>& other)
{
    _re += other._re;
    _im += other._im;
return *this;////// :)
}



1



AlisaChoi

0 / 0 / 0

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

Сообщений: 17

10.01.2017, 21:49

 [ТС]

4

Если вам return не нужен, то поставьте void и ничего не возвращайте.

Он все равно просил return..

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

C++
1
2
3
4
5
6
7
template <typename T>
inline Complex<T>& Complex<T>::operator+= (const Complex<T>& other)
{
    _re += other._re;
    _im += other._im;
return *this;////// :)
}

Спасибо за помощь) Заработало! Буду добавлять остальные запросы для этой проги)



0



Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

10.01.2017, 21:52

5

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

Заработало!

Сам люблю этот момент.)
Рад, что помог. Пишите.



0



AlisaChoi

0 / 0 / 0

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

Сообщений: 17

11.01.2017, 23:05

 [ТС]

6

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

Пишите.

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

C++
1
2
template <typename T>
 Complex<T> abs(const Complex<T>& _ComplexNum)

так и

C++
1
2
3
4
    float abs() // Модуль комплексного числа
    {
        return sqrt(_re * _re + _im * _im);
    }

Но он требует задать или сам модуль или корень.
А каким образом это можно прописать с оператором? Или вообще каким образом это выявляется?



0



2431 / 1831 / 404

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

Сообщений: 8,166

11.01.2017, 23:42

7

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

Для модуля можно ж использовать как

Вы сравните возвращаемые значения.
В одной — float, в другой — Complex<>.

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

А каким образом это можно прописать с оператором? Или вообще каким образом это выявляется?

Что вы понимаете под словом «это». Сформулируйте свои вопросы так, чтобы было понятно о чем речь.



0



0 / 0 / 0

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

Сообщений: 17

11.01.2017, 23:55

 [ТС]

8

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

Что вы понимаете под словом «это». Сформулируйте свои вопросы так, чтобы было понятно о чем речь.

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



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

12.01.2017, 00:01

9

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

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

Поскольку такого оператора нет то можно:

C++
1
2
3
4
template <typename T>
T Complex<T>::modulus(){
return pow(_re * _re + _im * _im, 0.5);
}

или в этом роде
#include <cmath>



1



S_el

2431 / 1831 / 404

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

Сообщений: 8,166

12.01.2017, 00:02

10

AlisaChoi, одним полноценным шаблоном, возвращающим тип double.

C++
1
return sqrt(_re * _re + _im * _im);

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



1



AlisaChoi

0 / 0 / 0

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

Сообщений: 17

12.01.2017, 17:54

 [ТС]

11

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

C++Выделить код

C++
1
2
3
4
5
6
7
8
1
2
3
4
template <typename T>
T Complex<T>::modulus(){
return pow(_re * _re + _im * _im, 0.5);
}

Простите за безграмотность, но выпадает ошибка C2039 modulus: не является членом «Complex<T>»
Как объявить modulus и исправить данную ошибку?



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

12.01.2017, 19:04

12

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

Простите за безграмотность, но выпадает ошибка C2039 modulus: не является членом «Complex<T>»
Как объявить modulus и исправить данную ошибку?

в области класса (в public) напишите:

C++
1
T  modulus();

ну, то есть, это просто метод, а не оператор и его нужно будет вызывать на экземпляре оператором доступа (точкой) как и любой метод. А имя можно и другое придумать magnitude, например, если modulus не понравится.



0



0 / 0 / 0

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

Сообщений: 17

12.01.2017, 19:20

 [ТС]

13

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

в области класса (в public) напишите

Спасибо! Теперь снова заработало буду разбираться с выводом модуля и преобразованием Эйлера сейчас..
Просто во всем не очень-то бум-бум.. Поэтому легкие программы все равно идут туго и требуют долгого времени на разбирательство.. Но это до жути интересно)



0



Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

12.01.2017, 19:23

14

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

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

Это всё ну, прямо, про меня.
Пишите.



0



AlisaChoi

0 / 0 / 0

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

Сообщений: 17

13.01.2017, 19:17

 [ТС]

15

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

Пишите.

И возник очередной вопрос)
Каким образом реализовать, чтобы следующий код функционировал? (Понятно, то нужно int во float переделать, а это можно вроде 3 способами, но вот как, чтобы работало — не знаю )

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "stdafx.h"
#include "complex.h"
 
int main()
{
    Complex<int> a(12, 34), b(12, -24);
    Complex<float> c;
 
    c = a;
 
    std::cout << a + b << std::endl << a - b << std::endl << a * b << std::endl << a / b << std::endl;
 
    std::cin.get();
 
    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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#ifndef __COMPLEX_H__
#define __COMPLEX_H__
 
#include <iostream>
#include <cmath>
 
template <typename T>
class Complex
{
    template <typename U>
    friend std::istream& operator >> (std::istream&, Complex<U>&);
 
 
public:
    explicit Complex(const T& re, const T& im);
    Complex(const Complex& other);
 
    Complex& operator=(const Complex& other);
 
    T real() const { return _re; }
    T imaginary() const { return _im; }
    T modulus();
 
    Complex conjugate() const { return Complex(_re, -_im); }
 
    Complex& operator+= (const Complex& other);
    Complex& operator-= (const Complex& other);
    Complex& operator*= (const Complex& other);
    Complex& operator/= (const Complex& other);
 
    
 
    Complex operator+ (const Complex& other);
    Complex operator- (const Complex& other);
    Complex operator* (const Complex& other);
    Complex operator/ (const Complex& other);
 
 
    bool operator== (Complex& other);
    bool operator!= (Complex& other);
    bool operator> (Complex& other);
    bool operator< (Complex& other);
 
bool operator > (const Complex<T>& other)
 
 
    {
        if (this->_re > other._re)
            return 1;
        else if (this->_re == other._re && this->_im > other._im)
            return 1;
        else
            return 0;
    }
 
bool operator < (const Complex<T>& other)
    {
        if (this->_re < other._re)
            return 1;
        else if (this->_re == other._re && this->_im < other._im)
            return 1;
        else
            return 0;
 
    }
 
bool operator != (const Complex<T>& other)
    {
        if (this->_re != other._re || this->_im != other._im)
            return 1;
        else
            return 0;
    }
 
bool operator == (const Complex<T>& other)
    {
        if (this->_re == other._re && this->_im == other._im)
            return 1;
        else
            return 0;
    }
 
private:
    T _re;
    T _im;
};
 
template <typename T>
inline Complex<T>::Complex(const T& re, const T& im)
    : _re(re), _im(im)
{
}
 
template <typename T>
inline Complex<T>::Complex(const Complex& other)
    : _re(other._re), _im(other._im)
{
}
 
template <typename T>
Complex<T>& Complex<T>::operator=(const Complex<T>& other)
{
    if (&other == this)
        return;
 
    _re = other._re;
    _im = other._im;
 
    return *this;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator+= (const Complex<T>& other)
{
    _re += other._re;
    _im += other._im;
 
    return *this;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator-= (const Complex<T>& other)
{
    _re -= other._re;
    _im -= other._im;
 
    return *this;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator*= (const Complex<T>& other)
{
    _re = _re * other._re - _im * other._im;
    _im = _im * other._re + _re * other._im;
 
    return *this;
}
 
template <typename T>
inline Complex<T>& Complex<T>::operator/= (const Complex<T>& other)
{
    _re = (_re * other._re - _im * other._im) /
        (other._re * other._re + other._im * other._im);
    _im = (_im * other._re - _re * other._im) /
        (other._re * other._re + other._im * other._im);
 
    return *this;
}
 
template <typename T>
T Complex<T>::modulus() {
    return pow(_re * _re + _im * _im, 0.5);
}
 
template <typename T>
inline Complex<T> Complex<T>::operator+ (const Complex<T>& other)
{
    return Complex<T>(*this) += other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator- (const Complex<T>& other)
{
    return Complex<T>(*this) -= other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator* (const Complex<T>& other)
{
    return Complex<T>(*this) *= other;
}
 
template <typename T>
inline Complex<T> Complex<T>::operator/ (const Complex<T>& other)
{
    return Complex<T>(*this) /= other;
}
 
 
template <typename T>
std::istream& operator >> (std::istream& in, Complex<T>& c)
{
    return in >> c._re >> c._im;
}
 
template <typename T>
std::ostream& operator<< (std::ostream& out, const Complex<T>& c)
{
    return out << "Re = " << c.real() << " " << "Im = "<< c.imaginary();
}
 
#endif //__COMPLEX_H__



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

13.01.2017, 21:24

16

AlisaChoi, возможность создавать комплексные числа на параметрах int, char, string и т.п это зло. Самый простой вариант для сложения инстансов разных типов:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;
template<typename T>
class Compl{
public:
T re_,im_;
Compl(T rea_, T img_):re_(rea_), im_(img_){}
 
template<typename U>
Compl& operator+(Compl<U>&);
};
 
template<typename T>
template<typename U>
Compl<T>& Compl<T>::
operator+(Compl<U>& rhs){
 
    re_+=rhs.re_;
    im_+=rhs.im_;
    return *this;
}
 
int main(int argc, char* argv[])
{
Compl<double> a(1,2);
Compl<float> b(2,3);
Compl<double>c(0,0);
c=a+b;
cout<<c.re_<<" "<<c.im_ <<endl;
system("pause");
return 0;
}

Но сложение, где первым слагаемым будет более узкий тип, будет приводить к усечению. Такое поведение интуитивно-живодерно-обрезающее и будет приводить к травмам.



0



AlisaChoi

0 / 0 / 0

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

Сообщений: 17

13.01.2017, 22:57

 [ТС]

17

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

Самый простой вариант для сложения инстансов разных типов

Что-то он немного вылетел у меня с ошибкой.. сначала, что

C++
1
#include "stdafx.h"

забыли.. а потом, что cout, endl и system не объявлены.
У меня вот по предложенному решению еще такой вопрос — это без отдельного класса делается, верно? Или все же

C++
1
class Compl

перенести отдельно (как делали до этого) ?



0



Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

13.01.2017, 23:00

18

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

забыли.. а потом, что cout, endl и system не объявлены.

я написал чтобы было понятно, а не чтобы было готово к употреблению. К тому же я не вижу смысла обеспечивать возможность одновременной работы инстансов класса созданных на разных типах чисел.
stdafx.h не использую, а с доступом через полное имя учитывающее пространство: std::cout и пр. не должно быть проблем. Укажите просто и всё.



1



0 / 0 / 0

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

Сообщений: 17

13.01.2017, 23:22

 [ТС]

19

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

Самый простой вариант для сложения инстансов разных типов

сначала спросила, потом сделала то о чем спросила
Заработало, если в отдельный класс все поместить..
Сейчас только переделать момент, когда одно нужно к другому приравнять. И, думаю, хватит уже мучить программу)
Пора открыть, наверное, новую тему с шарпом и ОГРОМНЕЙШИМ вопросом по еще одной программе)

Добавлено через 8 минут

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

я написал чтобы было понятно, а не чтобы было готово к употреблению.

Я это поняла, просто что-то запустила.. и из-за ошибок забыла, что вообще переделать хотела..
извиняюсь, за некомпетентность



0



IGPIGP

Комп_Оратор)

Эксперт по математике/физике

8776 / 4515 / 608

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

Сообщений: 13,468

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

16.01.2017, 13:32

20

AlisaChoi, там невнимательно я прочёл и понаписал. Ссылку возвращают операторы +=, -+, *=, /=, инкремент, декремент, присваивание…
А простые бинарные операции возвращают новый объект:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
template<typename T>
class Compl{
public:
T re_,im_;
Compl(T rea_, T img_):re_(rea_), im_(img_){}
 
Compl& operator+=(const Compl&);//тут ссылка возвращается
Compl operator+(const Compl&);//тут объект возвращается
 
template<typename U>
Compl operator+(const Compl<U>&);//и тут объект возвращается
};
 
template<typename T> 
Compl<T>& Compl<T>::
operator+=(const Compl& rhs){
    re_+=rhs.re_;
    im_+=rhs.im_;
    return *this;
}
 
 
template<typename T> 
Compl<T> Compl<T>::
operator+(const Compl& rhs){
Compl<T> ret(*this);
    ret.re_+=rhs.re_;
    ret.im_+=rhs.im_;
    return ret;
}
 
template<typename T>
template<typename U>
Compl<T> Compl<T>::
operator+(const Compl<U>& rhs){
Compl<T> ret(*this);
    ret.re_+=rhs.re_;
    ret.im_+=rhs.im_;
    return ret;
}
int main(int argc, char* argv[])
{
Compl<double> a(1,2);
Compl<float> b(2,3);
Compl<double>c(0,0);
c=a+b;
 
cout<<c.re_<<" "<<c.im_ <<endl;
system("pause");
return 0;
}

Простите за то, что запутал.
Если распутались, — напишите.



1



ostream &operator<<(ostream &os, const PT &p) {
    os << "(" << p.x << "," << p.y << ")";

}

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

Владимир Мартьянов's user avatar

задан 14 ноя 2017 в 12:31

user274179's user avatar

1

1 ответ

ostream& operator<<(ostream& os, const PT& p)
{
    os << "(" << p.x << "," << p.y << ")";
    return os;
}

ответ дан 14 ноя 2017 в 13:26

Jens's user avatar

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];
    };

Содержание

  1. Error c4716 visual studio
  2. Answered by:
  3. Question
  4. Answers
  5. All replies
  6. Error c4716 visual studio
  7. Answered by:
  8. Question
  9. Answers
  10. All replies
  11. Error c4716 visual studio
  12. Answered by:
  13. Question
  14. Answers
  15. All replies
  16. Русские Блоги
  17. Ошибка C4716 должна вернуть обработку значений
  18. вопрос
  19. решать
  20. Интеллектуальная рекомендация
  21. Реализация оценки приложения iOS
  22. JS функциональное программирование (е)
  23. PWN_JarvisOJ_Level1
  24. Установка и развертывание Kubernetes
  25. На стороне многопроцессорного сервера — (2) *
  26. Ошибки и предупреждения режима сборки проекта (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 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 …

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

Member Avatar


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.

Member Avatar

13 Years Ago

Why dont you use an array of pointers and return the array of pointers.

Member Avatar

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.

Member Avatar

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?

Member Avatar


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.

Member Avatar

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.

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.

Member Avatar

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.

Member Avatar


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!

Member Avatar

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 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 …

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

Member Avatar


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.

Member Avatar

13 Years Ago

Why dont you use an array of pointers and return the array of pointers.

Member Avatar

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.

Member Avatar

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?

Member Avatar


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.

Member Avatar

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.

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.

Member Avatar

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.

Member Avatar


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!

Member Avatar

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.

Понравилась статья? Поделить с друзьями:
  • Error c4430 missing type specifier int assumed note c does not support default int
  • Error c4235 nonstandard extension used asm keyword not supported on this architecture
  • Error c4065e type of input file
  • Error c3867 visual studio
  • Error c3861 strcpy identifier not found