I'm realy new to c++ and I've got a question.It might seem a question easy to find on the internet, but I've been looking for the awnser for 1 hour on the web now...
How do you turn the value of a double (lets say 3.1233512313) into a smaller decimal value (3.1 or 3.12 etc)? And how would you make the program know how many decimals there should be and how to round the number appropriately?
Thanks in advance!
(if it helps, here is the sourcecode I'd like to apply it on. Its a realy basic calculator:
//
// This is a simple calculator, capable of computing sums with: +,-,/,* and powers
//
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
//declare all variables used
double num1, num2, result;
int choice;
bool loop;
loop = true;
while(loop)
{
//welcome the user
cout << "****** Time to do some basic math!******" << endl;
cout << "________________________________________" << endl;
cout << endl;
cout<<"\nPress:\n*\t1 to add,\n*\t2 to subtract,\n*\t3 to multiply,\n*\t4 to divide,\n*\t5 to raise powers,\n*\t6 for sqroots.\n"<<endl;
cin>>choice;
switch(choice)
{
case 1:
cout << "Enter number 1: ";
cin >> num1;
cout<<"\nEnter number 2: ";
cin >> num2;
result = num1 + num2;
cout<<num1<<" + "<<num2<<" = "<<result<<endl;
break;
case 2:
cout << "\nEnter number 1: ";
cin >> num1;
cout<<"\nEnter number 2: ";
cin >> num2;
result = num1 - num2;
cout<<num1<<" - "<<num2<<" = "<<result<<endl;
break;
case 3:
cout << "\nEnter number 1: ";
cin >> num1;
cout<<"\nEnter number 2: ";
cin >> num2;
result = num1 * num2;
cout<<num1<<" * "<<num2<<" = "<<result<<endl;
break;
case 4:
cout << "\nEnter number 1: ";
cin >> num1;
cout<<"\nEnter number 2: ";
cin >> num2;
if(num2 == 0)
cout<<"Division by zero not allowed.\n"<<endl;
else
{
result = num1 / num2;
cout<<num1<<" / "<<num2<<" = "<<result<<endl;
}
break;
case 5:
cout << "\nEnter number 1: ";
cin >> num1;
cout<<"\nEnter the power you want to raise to: ";
cin >> num2;
result = pow (num1, num2);
cout<<num1<<" to the power "<<num2<<" = "<<result<<endl;
break;
case 6:
cout << "\nEnter the number: "<<endl;
cin >> num1;
if (num1 > 0)
{
num2 = sqrt(num1);
cout<<"The sqroot of "<<num1<<" = "<<num2<< endl;
}
else
{
cout<< "The sqroot of a number < 0 is not possible..."<<endl;
}
break;
default:
cout<<"Invalid input."<<endl;
}
system ("Pause");
system ("cls");
}
return 0;
}