C++ Program Outputting Wrong Number - c++

This is my program:
#include "stdafx.h"
#include <iostream>
using namespace std;
double areaofcircle(double r)
{
return 3.14 * r * r;
}
int main()
{
cout << areaofcircle(5);
}
I should be getting the output of "78.5" but I keep getting "78.512". What is going on?!
I've also tried float, but I still get the same output.
Also just a side question, do I really need to add "return 0;" to the main function?
One more side question, do I need to write "using namespace std;" inside every function, or can I just write it outside of everything, like how I've been doing it.

You're passing the literal for an integer (5) so somewhere an implicit conversion is required to turn it into a double. You would be better off passing 5.0. The C++ default for doubles requires no specifier so your 3.14 is fine. (specifying a float requires 3.14f). That said, I tried both with 5 and 5.0 and got 78.5 both times on my compiler.
How you're using the std namespace is fine, but as pointed out it does bring ALL of the standard namespace into scope. I see this a lot in teaching material. It is better to just use
using std::cout;
or just explicitly add std::cout to all uses. However, there is nothing "wrong" from a compilation standpoint in the way you did it.

I think you are doing something wrong. I tried the same on GCC compiler, and I do get 78.5. Which compiler are you using?
Regarding your other questions
It is always a good idea to return the state of your program from main. Usually, you can return EXIT_SUCCESS if everything works okay, else you can return EXIT_FAILURE.
No it is not necessary to include using namespace std. Instead, it is bad practice to pollute your standard namespace. You should include only those functions that you use very frequently.
To read more about C++. Check this link
Hope this helps.

Tried a few experiments on VS 2008 to see if I could get a similar error. By changing pi to a float I do get 78.500002622604370 which is different but not the same as your issue. But I do get 78.5 when pi is a double.
I'd recommend you let us know which compiler and version you're using, then possibly someone may be able to help.
#include "stdafx.h"
#include <iostream>
const double pi = 3.14;
double areaofcircle(double r)
{
return pi * r * r;
}
int _tmain(int argc, _TCHAR* argv[])
{
double temp = areaofcircle(5);
std::cout << temp;
return 0;
}

Related

CodeBlocks compilation error. Cin was not declared in this scope

When i want to compile a code, is giving me an error... cout and cin was not declared in this scope. What's the problem?
I searched on google. They said i need to reinstall codeblocks. I have done this and is not working.
#include <iostream>
int main()
{
int n,z,c;
cin>>n;
z=0;
while(n>0)
{
c=n%10;
n=n/10;
if(c<5)
{
z=z*10+2*c;
}
}
cout << z;
return 0;
}
It should compile it...
Just add this using namespace std; after #include <iostream> . Or use std::cin std::cout.
Also posting the 3rd way (compromise between the 2 existing answers - was already mentioned in the comments), which I think works best for the current scenario. This is my favorite one (well, excepting cases when I use lots of stuff from a namespace).
Add:
using std::cin;
using std::cout;
after the #include. This way:
You avoid using namespace X; hell. That's a big NO-NO, there are lots of resources explaining why (you could check [SO]: what is the reason for using a wildcard import? (#CristiFati's answer) for an equivalent in Python)
You don't have to type the fully qualified name every time (just the plain name). Using FQNs can be / is:
Very annoying (especially when dealing with nested namespaces)
Safe
Easier to read
Addding std::cin or std::cout would fix it
If you don't want to add std:: again and again then
You can also add using namespace std; just after #include<iostream>
This happens because cin and cout are members of standard library.

Implicit “using namespace std” without writing it in the source code

I have a C++ code that uses endl, vector, complex, and cout occasionally without any namespace qualification. When compiling with GCC 4.9, I get errors like this one:
bfm.h:454:4: error: 'complex' does not name a type
complex<double> inner(Fermion_t x,Fermion_t y);
^
In the very same file, there are lines with an std:: qualifier:
std::complex<Float> dot(Fermion_t x_t, Fermion_t y_t,int sx,int sy);
Throughout the codebase, I saw the following template specializations used
std::complex<double>
std::complex<cFloat>
complex<Float>
complex<double>
complex<T>
complex<S>.
Neither for the regular express struct\s+complex nor class\s+complex I managed to find something in the codebase or the codebase of the base library. Therefore I assume that it indeed is the standard library complex type.
There are a couple of using namespace std scattered around in various header files, but not all of them.
I tried compiling this codebase with GCC 4.9 and Clang 3.7. Both give similar errors about the missing type. Is there some possibility that this has worked with an older version of GCC? I have tried to insert std:: at all the needed points but I have the impression that I do something wrong if I cannot just compile the source checkout that is meant for this type of computer.
you can use selective using... declarations or type aliasing to bring in only the std:: members you need. Like:
using std::complex;
using std::cout;
using std::endl;
cout << "Hello world" << endl; // works
complex<float> x; // works
fstream y; // compile error, no namespace qualification, no using declaration
std::fstream z; // OK
Ah, yes, maybe not that evident, so perhaps worth mentioning. You now that std::endl? Well, it's a stream manipulator, a function in fact.
Which means one can bring in the current block function members from other namespaces as well.
Like:
#include <cmath>
#include <cstdlib>
inline void dummy(float x) {
float y=fabs(x); // Na'a.., fabs is imported into std namespace by <cmath>
using std::itoa; // same is itoa, but we'll be using it
char buff[128];
itoa(42, buff, 10); // OK
}

C++ math functions can be used without including the directive "math.h" in VS 2013

I am very curious why I can use the math functions in C++ without including the "math.h". I can't find an answer with google search.
Here is the simple code I am executing. Everything is compiling and running.
#include <iostream>
using namespace std;
int main()
{
const float PI = acosf(-1);
cout << PI << endl;
return 0;
}
Any standard header is allowed to include any other standard header.
if you would compile the same with gcc-4.8 it would complain.
Keep in mind that this is not something to rely on if you want your code to be portable and compilable on different versions of the same or different compilers.

Program failed to compile

Here is my code. I am using Dev-C++ 4.9.8.0 and I can not figure out why this wont compile.
#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
int main() {
int n; // Number to test for prime-ness
int i; // Loop counter
int is_prime = true; // Boolean flag...
// Assume true for now.
// Get a number form the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility
// by all whole numbers from 2 to sqrt(n).
i = 2;
while (i <= sqrt(n)) { // While i is <= sqrt(n),
if (n % i == 0) // If i divides n,
is_prime = false; // n is not prime.
i++;
}
// Print results
if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;
system("PAUSE");
return 0;
}
Im getting various error messages about overloading. Can someone please help me figure out why its not compiling correctly.
As predicted, the error is a result of a symbol clash between an std::sqrt and sqrt, due to your use of using namespace std;.
The header cmath has a function called std::sqrt, and the symbol name sqrt is being imported into your namespace because of your using namespace std;. Even though you are not including math.h, for some reason your compiler is importing that header as well, and math.h defines a sqrt function.
The compiler is complaining that it does not know which sqrt to use.
The correct solution to this is to not use using namespace std;. See also: Why is "using namespace std" considered bad practice?.
In your particular case, you can replace using namespace std; with the following:
using std::cout;
using std::cin;
using std::endl;
to avoid typing std:: in front of these all the time.
To be honest the compiler should not be including math.h, and as others have pointed out, using a 10+ year old compiler is just silly. Use a modern compiler.
Edit: Also, please, never again post half a dozen comments in a row to communicate a multi-line error message. Just edit your original post.
This compiles fine in gcc.
Although thre are some things you can improve like not including #include <stdlib.h> including stdlib instead of stdlib.h and making is_prime bool.
line 22 call of overloaded 'sqrt(int&)' is ambiguous
try sqrt<int>(n) or sqrt((int) n)
#Andrey gives you the answer: use ::sqrt(n) or std::sqrt(n) or include math.h instead of cmath. The best is still as he suggests: don't use using namespace std;.
My advice: switch to a more mainstream compiler like gcc, clang or Visual Studio. They better conform with the standard.
The book i am using uses Dev-C++
i don't want to be mean but switch to another book two. I wouldn't trust a book that makes you include stdlib.h. It's a header from the time that C wasn't standardized yet. So... yeah... switch the book...

Can This Code Compile? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
C++ void return type of main()
What is the proper declaration of main?
Simple question, really.
My friend and I are perusing the Powerpoint slides of a professor we are supposed to be hearing next semester. It will be a Java course. For some reason, he has this C++ code snippet
#include <iostream.h>
main ()
{ cout << "Hello, World\n"; }
I have told my friend, "No, this won't work with any modern C++ compiler."
My question is now, can this compile at all?
It could, sure.
Consider, for example, if <iostream.h> was a header with the following contents:
#include <iostream>
using std::cout;
#define main int main
That is not standard C++. The list of issues is quite long for a piece of code that short... probably because it comes from ages ago and an old non-conforming compiler.
The proper name of the include header is #include <iostream>, the .h was dropped during the ANSI standarization.
Types must be explicitly stated in C++. You cannot declare a function without return type and get a default int (that is C, not C++).
The standard signatures for main are: int main(), and int main( int argc, char** ) (implementations can provide extra arguments, but the return type must be int)
cout is defined inside the std namespace and cannot be used without qualification unless you add a using.
The equivalent code in proper C++ would be
#include <iostream>
int main() {
std::cout << "Hello world\n";
}
This will compile, though any decent compiler should raise a warning. Since you're using #include <iostream.h>, the compiler assumes that this is old code and compiles it in backwards-compatible mode. On my machine, gcc says:
In file included from /usr/include/c++/4.2.1/backward/iostream.h:31,
from oldcpp.cpp:1:
/usr/include/c++/4.2.1/backward/backward_warning.h:32:2: warning:
#warning This file includes at least one deprecated or antiquated header.
Please consider using one of the 32 headers found in section 17.4.1.2 of the C++
standard. Examples include substituting the <X> header for the <X.h> header for C++
includes, or <iostream> instead of the deprecated header <iostream.h>.
To disable this warning use -Wno-deprecated.
But it still compiles it fine. On running the code, I get exactly what is expected: i.e.:
Hello, World
Is this even worth questioning? Why write corner-case C/C++? What's wrong with keeping with the standards? main() is the entry point of the program, and the OS expects a return code from the program. Now there are arguments whether void main() is acceptable, but why even defend it? Just use int main() and be a happy dude that writes good code:
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << "Hello World!\n";
return 0;
}
I start every program with this (without the HW! then) and never ever had any issues.