By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,480 Members | 763 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,480 IT Pros & Developers. It's quick & easy.

error: invalid operands of types ‘float’ and ‘void’ to binary ‘operator+’

P: 1
It seems to me that there is an error in type n, but whatever type I put it still appears, just change to int n, float n, double n, but it still does not work.
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <cmath>
  3. #include<math.h>
  4. #include<time.h>
  5.  
  6. using namespace std;
  7.  
  8. void func(float n) 
  9. {
  10.     if(n <= 1){
  11.         cos(1);
  12.     }else{
  13.          cos(n + func(n - 1));   
  14.     }
  15.  
  16. }
  17.  
  18. int main ()
  19. {
  20.     func(15);
  21. }
May 27 '19 #1
Share this Question
Share on Google+
3 Replies


dev7060
P: 91
Library function cos() requires double type actual parameter to work on. For the statement, cos(n + func(n - 1)), n is of float type but the function calling part is not returning any value because of function, having the return type 'void'. Therefore, cos(float + void) doesn't make any sense for the binary operator '+'. Change the return type of the function to make the whole expression producing a uniform data type result.
May 27 '19 #2

P: 10
your func(float n) function should be float too because the binary operator '+' needs the second value to be same with the first one (float) , but it detected void, that's the problem. My suggestion to the code:
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<cmath>
  3. #include<math.h>
  4. //cmath for cpp, math.h for c. only keep one.
  5. #include<time.h>
  6.  
  7. using namespace std;
  8.  
  9. float func(float n) 
  10. {
  11.     if(n <= 1){
  12.         return cos(1);
  13.     }
  14.     else{
  15.          return cos(n + func(n - 1));   
  16.     }
  17. }
  18.  
  19. int main ()
  20. {
  21.     cout<<func(15);
  22.     return 0; //this is a good habit. It'll be better for you when throwing errors and returning values other than 0
  23. }
  24.  
I suggest that you only keep one of cmath and math.h in the program, and change time.h to ctime because thats more c++-ish
Jul 9 '19 #3

P: 1
the value before and after operator '+' should be the same type, your n is a float but func() does not return float.
4 Weeks Ago #4

Post your reply

Sign in to post your reply or Sign up for a free account.