| >
| > The sign of an integer is part of the variable itself, there is no
need
| > to compute anything.
| >
| > bool sign(int n)
| > {
| > return n >= 0;
| > }
| >
|
| How do mathematicians decide the sign of 0 if -0 = 0? Your function
says -0
| is positive.
|
You asked specifically about Integers.
The function says nothing, there is no such thing as a negative integer
with a value of 0. So forget the function. It doesn't matter whether
sign(...) returns n > 0 or n >= 0.
An integer does not support that which you are asking for. The
mathematician has the choice of using an integer or devising his/her own
numbering system.
But beware, this means he needs to realize whats involved. In other
words: whats the result of -0 + (+0) = ??? or -10 - (+10) = ??? or +0 /
(-10) = ???. Thats an implementation detail that someone has to deal
with.
In the class below, the sign is being store in a primitive boolean
member. The value is in an unsigned integer member. I've not even
defined the operators required to support such a number system (ie:
operator+, operator-, operator=, operator+=, operator-=, operator/,
operator*, etc).
// Proj_SignedInteger.cpp
#include <iostream>
#include <ostream>
#include <vector>
class SignedInteger
{
bool m_bsign;
unsigned m_u;
public:
/* ctors */
SignedInteger() : m_bsign(true), m_u(0) { }
SignedInteger(bool b, unsigned u) : m_bsign(b), m_u(u) { }
/* copy ctor */
SignedInteger(const SignedInteger& copy)
{
m_bsign = copy.m_bsign;
m_u = copy.m_u;
}
/* d~tor */
~SignedInteger() { }
/* friends */
friend std:
stream&
operator<<(std:
stream&, const SignedInteger&);
};
std:
stream&
operator<<(std:
stream& os, const SignedInteger& si)
{
os << (si.m_bsign ? "pos " : "neg ");
os << si.m_u;
return os;
}
int main()
{
SignedInteger si_pos_0; // default ctor will suffice, pos 0
SignedInteger si_neg_0(false, 0); // neg 0
SignedInteger si_pos_10(true, 10); // pos 10
SignedInteger si_neg_10(false, 10); // neg 10
std::vector< SignedInteger > vsi; // a vector container of si
vsi.push_back(si_pos_0);
vsi.push_back(si_neg_0);
vsi.push_back(si_pos_10);
vsi.push_back(si_neg_10);
for(unsigned u = 0; u < vsi.size(); ++u)
{
std::cout << "vsi[" << u << "] = " << vsi
;
std::cout << std::endl;
}
return 0;
}
/*
vsi[0] = pos 0
vsi[1] = neg 0
vsi[2] = pos 10
vsi[3] = neg 10
*/