Hi all. I am brand new to C++. Just started taking an online course and have been reading the tutorials and forums here.
For my first program, I decided to write a simple tax calculator. I used some of the code from the tutorials section here to start me out, and then adapted it, using what I have learned so far to do so.
My problem is, I have my code nice and compact now (which I like!), but as you can see, I had to use multiple 'else if' statements, to accomplish my goal ,because of the way 'setprecision' works.
My question is....is there any other way to do this that would help me compact my code?
#include <iostream>
#include <new>
#include <iomanip>
usingnamespace std;
main ()
{
int i, n;
float a, b, * p, sum=0;
cout << "How many items would you like to enter? ";
cin >> i;
p= newfloat[i];
for (n=0; n<i; n++)
{
cout << "Enter price: ";
cin >> p[n];
}
{
for (n=0; n<i; n++)
sum+=p[n];
}
a = sum * 9.5 / 100;
b = sum+=p[n] + a;
delete[] p;
if (b < 9.99) {
cout << "Your grand total is: " << setprecision(3) << b << endl;
}
elseif (b > 9.99 && (b < 99.99)) {
cout << "Your grand total is: " << setprecision(4) << b << endl;
}
elseif (b > 99.99 && ( b < 999.99)) {
cout << "Your grand total is: " << setprecision(5) << b << endl;
}
elseif (b > 999.99 && ( b < 9999.99)) {
cout << "Your grand total is: " << setprecision(6) << b << endl;
}
else {
cout << "Your total must be under $10,000.00!" << endl;
}
return 0;
}
#include <iostream>
#include <new>
#include <iomanip>
// using namespace std; // *** avoid
int main () // *** int main()
{
// int i, n; // *** postpone declaring names till they are actually required
// /*float*/ double a ; // *** use double as the default floating point type
// double b ; // *** one declaration per line
std::cout << "How many items would you like to enter? ";
int nitems ;
std::cin >> nitems;
// double* p = new double[i];
double sum = 0;
for( int n = 0; n < nitems ; ++n )
{
std::cout << "Enter price: ";
double number ;
std::cin >> number ;
sum += number ;
}
constdouble a = sum * 9.5 / 100;
constdouble b = sum + a;
// delete[] p;
std::cout << std::fixed << std::setprecision(2) // fixed point format, 2 digits after decimal point
<< "Your grand total is: " << b << '\n' ;
}
May I ask....why should I avoid 'using namespace std;' in exchange for 'std::cout', for example. As this is what I am learning in my online course.
Section 18.2 pg 990 of C++ Primer 5th edition details the answer you're looking for, but generally libraries don't use long convoluted names anymore and namespace provides a much more succinct means, but namespaces defined in global space can lead to namespace pollution. So for larger projects and those beyond the scope of C++ libraries is probably better to use implicit notation "std::cin" as you might be using something like "whatever::cin" without knowing it because it was defined deep inside a header file.