(C++) Add int and/or double and display sum - c++

So I have just completed "Sum of two numbers" on SPOJ. My code passed the test cases; however, it doesn't seem very elegant to me. My first approach was to try implementing a template to handle multiple data types. I could not figure out how to successfully do this.
My question: How could this program be written so that it makes use of a class as well as a function template (which handles int and double). I feel that using floor() is a bit weird, inappropriate. If using a template is not a good solution then a better one would be nice to see as well. Thanks.
EDIT:
The solution below works just fine. I am very interested in learning more about classes (OOP is new to me) and I would also like to learn more about templates. Here is a link to the problem on SPOJ: http://www.spoj.com/problems/CHITEST1/
My code:
//For t test cases, output the sum of two numbers
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
double a, b, sum;
cin >> a >> b;
sum = a + b;
if (sum != floor(sum)) cout << sum << endl;
else cout << static_cast<int>(sum) << endl;
}
return 0;
}

First, I'd say that applying !=/= to floating-point types is very dangerous. Even if you're using floor. Use comparisons to some very low epsilon value. (if (abs(a - b) < eps), where epsilon is something like 0.00001, depending on your desired precision).
Second, I don't really understand the idea of floor being here, because noshowpoint cout modifier is enabled by default, which means, 3.3 + 4.7 should print exactly 8, if it calculated without any errors - not 8.00000(I wouldn't rely on that, because it can result in 7.99999998 or 8.00000001 as well). Floor has the same level of reliability, because floor(7.999998) is 7, not 8. To be honest, I'd use round here.
Third, if you want to learn OOP or templates, these are not the tasks you want to do. This site looks like too much of a contest-related, and you're in need of educational info. Look here: http://www.cplusplus.com/doc/tutorial/

Maybe you are looking for this:
#include <iostream>
using namespace std;
template <typename T>
void getAddAndPrint()
{
T a, b;
cin >> a >> b;
T sum = a + b;
cout << sum << endl;
}
int main() {
// your code goes here
getAddAndPrint<double>();
getAddAndPrint<int>();
return 0;
}

Related

how could i manage to get answer in complex number from my code

I have write this code to solve a quadratic formula but it doesn't work when the answer is complex(in iota form like 3i or √-3) i want to get answer in iota how could i manage it
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float a,b,c,variable1,variable2,variable3,y,x,variable4;
cout<<"Enter a:";
cin>>a;
cout<<"Enter b:";
cin>>b;
cout<<"Enter c:";
cin>>c;
variable1=-b;
variable2=b*b;
variable3=(4*a*c);
variable4=(variable2-variable3);
y=sqrtf(variable4);
x=(variable1+y)/2;
cout<<"x=" <<x <<endl;
}
The overload of std::sqrt that produces a complex result is declared in <complex> and takes a std::complex<T> as its argument, so to get a complex result, you need to start with a complex input, and include the correct header.
Here's a trivial example:
#include <complex>
#include <iostream>
int main() {
std::complex<double> d{ -1, 0 };
std::cout << std::sqrt(d);
}
Result:
(0,1)
Those represent the real and imaginary parts respectively, so this is 0+1i, as we'd expect.
It may also be worth noting that starting with C++ 14, the standard library defines a user-defined literal for imaginary numbers, so you could initialize d like this:
using namespace std::literals;
auto d = -1.0 + 0i;
This produces the same result, but for people accustomed to writing a complex number as a + bi, it may look a little more familiar/comfortable. The one "trick" is that it's still doing type deduction, so to get a complex<double>, you need to use -1.0 instead of -1 (which I guess would try to deduce a std::complex<int>).

How do I accept 0 as an integer and not a bool value?

I'm trying to validate user input for integers only. My code works fine except when the user inputs 0. It doesn't consider it an integer, and it thinks the value is false. Here's a brief example of how I'm coding this project....
int main ()
{
int num;
cout << "Please enter an integer: ";
cin >> num;
cout << endl;
while (! num)
{
cout << "That is not an integer.\n";
return;
}
}
If the user inputs 0, I get sent into the while loop even though 0 is an integer.
The expression !num is true if, and only if, num is 0. So your implementation is buggy.
The easiest thing to do is to use something like
if (!(std::cin >> num)){
std::cout << "That is not an integer.\n";
}
If you want to validate the input yourself then consider reading in a std::string and checking if that can be converted to an integer. This is surprisingly non-trivial since the possible values an int can take are so platform dependent (some systems have a range as small as -32767 to +32767).
If you can, use boost::lexical_cast<int>(num); where I've upgraded num to a std::string type. (The header you need is <boost/lexical_cast.hpp>).
In c++ the built-in int type doesn't have any optional validity to it like it does in some other languages: "!num" just means "num==0" and not "num does not exist".
However C++17 has std::optional template, which can turn your vanilla int into exactly what you originally expected!
All you need is some simple template magic to make it work with istream:
template< class CharT, class Traits, class T >
basic_istream<CharT,Traits>& operator>>( basic_istream<CharT,Traits>&& st,
std::optional<T>& value )
{
T res;
st>>res;
value = (st)?res:{};
return st;
}
Come to think of it, STL should provide that overload from the box.
Now all you need is to replace your int num with std::optional<int> num and voila - your code works as intended.
Seriously though, just use Bathsheba's solution.

Implicit casting acting strange

I have a question about implicit casting for the following code
#include <iostream>
using namespace std;
float max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int main() {
double a, b;
cin >> a >> b;
cout << max(a, b)<<endl;
cout << a;
return 0;
}
Now Supposing that a = 30.5 & b = 26.4.
The anticipated result is 30 however on one computer(MinGW & VS 2005) I get 30.5.
Does anyone have an interpretation for this ? It makes no sense to me.
Edit 1 :
on third line output is 30.5 instead of the anticipated 30
Solution
std::max() is shadowing it, but why it shadows it on one computer and it doesn't on another I didn't investigate in that.
So try to avoid naming your functions or classes with names reserved for the standard library.
This is whats resulting in the weird output:
using namespace std;
When calling max() you may be calling std::max() which may be included in <iostream> with no guarantees. Try this:
cout << ::max(a, b)<<endl; //forces global scope
Should print out 30.

C++ Programming Error: expected unqualified-id before "{" token

I am a newbie at C++, and I am trying to make a "calculator" which: adds two numbers, subtracts two numbers, multiplies two numbers, divides two numbers, takes the sine of a number, takes the cosine of a number, or takes the tangent of a number. Here is the code:
#include <iostream>;
#include <cmath>;
#include <string>
int main ()
{}
int ask(std::string operation);
{
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::cin>>operation;
if (operation="Addition")
{
goto Add
}
float Add(float addend1, float addend2, float answer)
{
Add:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
break
}
}
There will be more functions later, but my problem is on line 7. There is an error that says: expected unqualified-id before "{" token. I know my indentation is horrible, but thanks!
You have a lot of issues in your code.
First, as Ivan points out, you are trying to define a function inside of a function (ask() inside main()). That isn't valid.
Second, you have a goto (why?!) attempting to jump to a label in another function. I doubt your compiler will even allow that, but how would you expect that to work? You are attempting to use variables passed to your function addition that don't exist as you never call the function and the stack has never been setup for it. This is bad, don't do it, just call the function properly.
Third, the #include preprocessor directive is terminated with a newline, not a semicolon. That could cause some (relatively) hard to track down compilation errors.
Fourth, you are mistakenly attempting to assign the const char* "Addition" to operation when what you meant to use was the equality operator ==. That won't work ether though because operation is an r-value and cannot be assigned to like that. If you want to modify it you will need to declare it as a pointer, but once again, that's not what you are going for semantically...
If you want to compare strings and (for whatever reason...) are intent on using pointers to char then you should be using strcmp. That said, you are in C++ land, so just use std:string instead.
Try something like this. I haven't enhanced your code in anyway, just made it something that will compile and run. I have made a few changes.
Aside from getting rid of a few syntax errors, your original Add function took the result as a float argument. Assigning to that from within the function would only modify a copy. You would need to take a pointer or reference if you want the caller to see the modified value, but you don't need that at all as you can simply return the result.
The string comparison is case sensitive, so you would probably want to change it to be case insensitive. I'm assuming no localization here :). I'm not performing error checking on the input either, so be aware that it may fail if the user enters something other than a valid floating point number.
#include <iostream>
#include <string>
using namespace std;
void Ask();
float Add( float, float );
int main( size_t argc, char* argv[] )
{
Ask();
return 0;
}
void Ask()
{
cout << "Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
string operation;
cin >> operation;
if( operation == "Addition" )
{
float first = 0, second = 0;
cout << "enter first operand";
cin >> first;
cout << "enter second operand";
cin >> second;
cout << "The result is: " << Add( first, second );
}
}
float Add( float first, float second )
{
return first + second;
}
С++ doesn't allow nested functions. You have function main() and trying to declare function ask() inside it. And compiler doesn't know what you want.
I commented your code a little bit, maybe that gets you started:
#include <iostream>;
#include <cmath>;
#include <string>;
int main () {
int ask (){ //you cannot nest functions in C++
char operation [20]; //why not use the string class if you include it anyway
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){ //you cannot compare char-strings in C++ like that
goto Addition; //don't use goto (I don't want to say "ever", but goto is only used in extremely rare cases) make a function call instead
}
}
float addition(float addend1, float addend2, float answer) //you probably want to declare the variables inside the function
{
Addition: //don't use labels
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Let's try to break this down..
You shouldn't use ; on the precompiler directives.
#include <iostream>;
#include <cmath>;
#include <string>;
Should be
#include <iostream>
#include <cmath>
#include <string>
.
int main () {
int ask (){
See Ivans answer for this
char operation [20];
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std:cin>>operation;
if (operation="Addition"){
You can use std::string instead which is alot easier to deal with. Then you can write
#include <string>
...
std::cout<<"Type Addition, Subtraction, Multiplication, Division, Sine, Cosine, or Tangent:\n";
std::string myString;
getline(cin, myString);
if (myString == "Addition"){
.
goto Addition;
}
}
float addition(float addend1, float addend2, float answer)
{
Not sure what is going on here.. but let's break Addition to it's own function
void Addition(){
// do addition here
}
.
Addition:
std::cout<<"Insert the first number to be added:\n";
std::cin>>addend1;
std::cout << "Insert the second number to be added:\n";
std::cin>>addend2;
answer=addend1+addend2;
std::cout<<addend1<<"+"<<addend2<<"="<<answer<<"\n";
}
Don't forget that you have to define the variables
int addend1;
int addend2;
int answer;
Hope this helps you along the way.
First int ask() what is that.Why do you start a block here.
Second you have two {s and three }s that's because of the ask().
I think that c++ does not support anonymus functions.
Third why do you use goto,when you have a function,just call the function.
Fourh your addition func should either be void or remove it's last parameter.
Also I think that you don't need string.h file unless you use some rather advanced funcs,the char array should be enough for your program.

Can I define a type based on the result of some calculation?

I perform some calculations, based on the result, I would like to either use a short int or int for some type of data for the remaining program. Can (/How can) this be done sensibly in C or C++? I don't really care about the amount of memory used (i.e., 2 or 4 bytes), my primary aim is to access generic arrays as if they contained data of this type. I would like to avoid code such as the following:
char s[128];
if (result of preliminary calculations was A)
*((int*) s) = 50;
else
*((short int*) s) = 50;
to set the first 4 or 2 bytes of s. A conditional global typedef would be ideal:
if (result of preliminary calculations was A)
typedef int mytype;
else
typedef short int mytype;
I am not that familiar with C++ class templates (yet). Do they apply to my problem? Would I have to change the declarations throughout my program (to myclass< > and myclass< >*)?
Many thanks!
Frank
Edit: The values may not always be aligned. I.e, a int can start at position 21. Thanks for the answers.
For plain C, you could do this using function pointers:
static union { s_int[32]; s_short[64]; s_char[128]; } s;
static void set_s_int(int i, int n)
{
s.s_int[i] = n;
}
static int get_s_int(int i)
{
return s.s_int[i];
}
static void set_s_short(int i, int n)
{
s.s_short[i] = n;
}
static int get_s_short(int i)
{
return s.s_short[i];
}
static void (*set_s)(int, int);
static int (*get_s)(int);
Set them once based on the preliminary calculations:
if (result of preliminary calculations was A)
{
set_s = set_s_int;
get_s = get_s_int;
}
else
{
set_s = set_s_short;
get_s = get_s_short;
}
Then just use the function pointers in the rest of the program:
set_s(0, 50); /* Set entry 0 in array to 50 */
Your file writing function can directly reference s or s.s_char depending on how it works.
In C and C++, all type information is defined at Compile-time. So no, you cannot do this.
If the result of the preliminary calculations can be found at compile time, then this can work. Here are some simple examples to show how this can work. To do more complicated examples, see http://en.wikipedia.org/wiki/Template_metaprogramming
using namespace std;
#include <iostream>
template<int x> struct OddOrEven { typedef typename OddOrEven<x-2>::t t; };
template<> struct OddOrEven<0> { typedef short t; };
template<> struct OddOrEven<1> { typedef int t; };
template<bool makeMeAnInt> struct X { typedef short t; };
template<> struct X<true> { typedef int t; };
int main(void) {
cout << sizeof(X<false>::t) << endl;
cout << sizeof(X<true>::t) << endl;
cout << sizeof(OddOrEven<0>::t) << endl;
cout << sizeof(OddOrEven<1>::t) << endl;
cout << sizeof(OddOrEven<2>::t) << endl;
cout << sizeof(OddOrEven<3>::t) << endl;
cout << sizeof(OddOrEven<4>::t) << endl;
cout << sizeof(OddOrEven<5>::t) << endl;
}
I think above is standard C++, but if not I can tell you this work on g++ (Debian 4.3.2-1.1) 4.3.2
I think your main problem is how you plan to read the data from s later on if you don't know what type to read.
If you have that part covered, you can use a union:
union myintegers
{
int ints[32];
short shorts[64];
};
Now simply use the type you want.
myintegers s;
if (result of preliminary calculations was A)
s.ints[0] = 50;
else
s.shorts[0] = 50;
As a step further, you could wrap it all in a class which is constructed with result of preliminary calculations was A and overrides the operators * and [] to store in one or the other.
But are you sure you want any of that?
In current C++ standard (C++03), you can't.
In fact you can use some advanced metaprogramming tricks but it will not help most of the time.
In the next standard (C++0x, certainly C++11 in the end), you will be able to use the keyword decltype to get the type of an expression. If you're using VC10 (VS2010) or GCC 4.4 or more recent, then you already have the feature available.
You could abuse templates for this purpose. Any code that's subject to the decision would have to be templated based on the int type. One branch would instantiate the int version, the other would instantiate the short int version. This is probably a bad idea*.
Edit
*Well, it's only a bad idea to apply this to your overall architecture. If you have a particular data type that encapsulates the varied behavior, a template should work just fine.
Here's a variation on Aaron McDaid's answer to illustrate it's use with conditions:
#include <iostream>
#include <string>
using namespace std;
template<int x> struct OddOrEven { typedef typename OddOrEven<x-2>::t t; };
template<> struct OddOrEven<0> { typedef short t; };
template<> struct OddOrEven<1> { typedef int t; };
int main() {
cout << "int or short? ";
string which;
cin >> which;
if (which.compare("int") == 0)
cout << sizeof(OddOrEven<1>::t) << endl;
else if (which.compare("short") == 0)
cout << sizeof(OddOrEven<0>::t) << endl;
else
cout << "Please answer with either int or short next time." << endl;
return 0;
}
This is a code snippet from a project I had a while back.
void* m_pdata;
if (e_data_type == eU8C1){
pimage_data = new unsigned char[size_x * size_y];
}
if (e_data_type == eU16C1){
pimage_data = new unsigned short[size_x * size_y];
}
I hope it can help you
Since your stated goal is to store information efficiently on disk, you should learn to stop writing memory images of C/C++ data structures to disk directly and instead serialize your data. Then you can use any of a number of forms of variable-length coding ("vlc") to get the effect you want. The simplest is a coding with 7 bits per byte where the 8th bit is a continuation flag indicating that the value is continued in the next byte. So 259 would be stored as (binary, with continuation bit marked by spacing and byte boundaries marked by ;):
1 0000010 ; 0 0000011
Alternatively you could use the head nibble to signal the number of bytes that will follow, or use a scheme similar to UTF-8 with slightly more overhead but stricter resynchronization guarantees. There are also vlcs with are designed to be parsable and easily resynchronized when reading either forward or in reverse.