2

Usually a C++ program will be having int main(). I have a simple program to add two numbers and return the value as follows:

int main(int argc, char *argv[])
{

    float num1 = 10.2;
    float num2 = 15.3
    float result = num1+num2;        
    return result;
}

I am getting the result returned as 25. But thee actual result is 25.5. I tried float main(). It is not allowd on C++. How can I return float value??

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97
  • stop playing `float main()`, try float a normal function – billz Apr 22 '15 at 11:54
  • 1
    What are you trying to return the `float` *to*? – Barry Apr 22 '15 at 11:56
  • You cannot return float from main. Check this [link](http://stackoverflow.com/questions/8844915/what-happens-if-main-does-not-return-an-int-value) – Manoj Kumar Apr 22 '15 at 11:56
  • 1
    The value returned from main is the 'exit' code of the program which can be interpreted by e.g. an OS, where return code 0 usually means that the program exited normally. To "return" a float from a C++ program I would print it to e.g. the standard output stream and have the other program catch that. – Banan Apr 22 '15 at 11:58

1 Answers1

3

Return type of your function main is int. You can't return any other type from main() and there may not be any usage of such too. But any other function can return a float value.

#include <iostream>

float sum(float a, float b)
{
    return a+b;
}
int main(int argc, char *argv[])
{

    float num1 = 10.2;
    float num2 = 15.3;
    float result = sum(num1,num2);
    std::cout<< result;
    return 0;
}
Steephen
  • 14,645
  • 7
  • 40
  • 47