Why my code is going wrong in C++?

+1 vote
asked Apr 17, 2018 by anonymous
Why the following code is wrong?

int main()
{
int f(int n)
{
  int p;
  if(999 % n == 0){
      p=999/n;
  }
  if(999 % n !=0){
      p=(999-(999 % n))/n;
  }
  return n*(p*(p+1)/2);
}

cout<<f(3);
}

4 Answers

0 votes
answered Apr 20, 2018 by Abhishek26 (440 points)
 
Best answer

You can not define function inside main function . 

Please check this :

int f(int n)
{
  int p;
  if(999 % n == 0){
      p=999/n;
  }
  else if(999 % n !=0){
      p=(999-(999 % n))/n;
  }
  return n*(p*(p+1)/2);
}

int main()
{
 std::cout<<f(3);

  return 0;
}

commented Apr 20, 2018 by anonymous
Thanks. It works :)
0 votes
answered Apr 17, 2018 by AQUA Play (500 points)
i am still learning C++  but try this

#include <iostream>

using namespace std;

int main()
{
int a;
int n;
{
  int p;
  if(999 % n == 0){
      p=999/n;
  }
  if(999 % n !=0){
      p=(999-(999 % n))/n;
  }
  return n*(p*(p+1)/2);
}

cout<<(3);
}
commented Apr 18, 2018 by anonymous
No, that's wrong :(
0 votes
answered Apr 18, 2018 by Soumya Ranjan (180 points)

int main()
{   int x;
int f(int n)
{
  int p;
  if(999 % n == 0)

  {
      p=999/n;
  }
  else

  {
      p=(999-(999 % n))/n;
  }
  return n*(p*(p+1)/2);
}
x=f(3);         //As the fn is returning a value, it must be held by some other temp varbl of same return type
cout<<x;
}

0 votes
answered Apr 18, 2018 by Soumya Ranjan (180 points)

int main()
{     int x;
int f(int n)
{
  int p;
  if(999 % n == 0)

  {
      p=999/n;
  }
 else

 {
      p=(999-(999 % n))/n;
  }
  return n*(p*(p+1)/2);
}
x=f(3);                    //As the fn returns a value,it must be held somewhere in the                                                  //   memory by a temp variable.  
cout<<x;
}

commented Apr 18, 2018 by anonymous
Thanks. But it doesn't still work. I run it  in an online compiler right here

https://www.onlinegdb.com/online_c++_compiler
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...