BasicMath implementation on C++
Advantages:
* Works with double
* Checks for incorrect input
Disadvantages:
* Uses namespace std. Big amount of libraries inside of it.
Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
double result;
double test;
if ((argc != 4) || (strlen(argv[2]) != 1) || (sscanf_s(argv[1],"%d", &test) != 1) || (sscanf_s(argv[3], "%d", &test) != 1))
{
cout << "<number> <+-x/> <number><ENTER>\n";
return 1;
}
else
{
if (argv[2][0] == '+')
result = atof(argv[1]) + atof(argv[3]);
else if (argv[2][0] == '-')
result = atof(argv[1]) - atof(argv[3]);
else if (argv[2][0] == 'x')
result = atof(argv[1]) * atof(argv[3]);
else if (argv[2][0] == '/')
{
if (atof(argv[3]) == 0)
{
cout << "Divide by zero is not possible";
return 2;
}
else
result = atof(argv[1]) / atof(argv[3]);
}
else
{
cout << "<number> <+-x/> <number><ENTER>\n";
return 1;
}
cout << result << "\n";
return 0;
}
}
Advantages:
* Works with double
* Checks for incorrect input
Disadvantages:
* Uses namespace std. Big amount of libraries inside of it.
Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
double result;
double test;
if ((argc != 4) || (strlen(argv[2]) != 1) || (sscanf_s(argv[1],"%d", &test) != 1) || (sscanf_s(argv[3], "%d", &test) != 1))
{
cout << "<number> <+-x/> <number><ENTER>\n";
return 1;
}
else
{
if (argv[2][0] == '+')
result = atof(argv[1]) + atof(argv[3]);
else if (argv[2][0] == '-')
result = atof(argv[1]) - atof(argv[3]);
else if (argv[2][0] == 'x')
result = atof(argv[1]) * atof(argv[3]);
else if (argv[2][0] == '/')
{
if (atof(argv[3]) == 0)
{
cout << "Divide by zero is not possible";
return 2;
}
else
result = atof(argv[1]) / atof(argv[3]);
}
else
{
cout << "<number> <+-x/> <number><ENTER>\n";
return 1;
}
cout << result << "\n";
return 0;
}
}
No comments:
Post a Comment