FIXED: The function that recieved the num variable and printed it on the calculator screen, recieved an "int" parameter
I'm a beginner and trying to make a calculator on console. You have to type each number just like in real calculators and they appear on the left.
This is the function to get digits of the next input so I know how many 0's I have to run.
int getDigits(int number)
{
int getDigits = 0;
while (number) {
number /= 10;
getDigits++;
}
return getDigits;
}
UPDATED GETDIGIT FUNCTION
long long getDigits(long long number)
{
long long getDigits = 0; //i know long long wasn't needed here
while (number) {
number /= 10;
getDigits++;
}
return getDigits;
}
The main number displaying on the calculator screen is a long long "num" and it changes every do while iteration.
case 1:
long long aux, aux2;
cout << "Number: "; cin >> aux;
aux2 = pow(10, getDigits(aux));
num *= aux2;
num += aux;
break;
This just takes the second input places it on the right. It works perfectly but
in this case when "num" excel 11 variables, it just becomes a negative number (i have no idea why, i did the operations manually and it should work fine). For example:
input: 1
num = 1
input: 2
num = 12
but when it reaches 11 digits
num = 12345678911
input = 1
num = -538112777 (instead of the 123456789111)
Why is this? all my variables are long long and should be enough, help really appreciated.
Integers in C++ have limited capacity. Going beyond the capacity or range results in an overflow.
An overflow could wrap around and become negative. The platform could generate an overflow exception.
Looking closely on your code, firstly
{
int getDigits(int number)
{
int getDigits = 0;
while (number) {
number /= 10;
getDigits++;
}
return getDigits;
}
You are passing getDigits(long long aux) to getDigit function thats is wrong.
Futhermore : why value become negative: the 8 bits are used to store character in which the RMB thats 8th from right to left and 1st from left to right when the value exceed binary 127 the right most bit is set which makes the value negative. The same happens to all the datatypes that are signed
FIXED: The function that recieved the num variable and printed it on the calculator screen, recieved an "int" parameter
I have a class with a data member that needs to be rounded up to a 2 digit integer, irrespective of the number of the input digits.
For example:
roundUpto2digit(12356463) == 12
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.
Currently my code looks like:
int roundUpto2digit(int cents){
// convert cents to string
string truncatedValue = to_string(cents);
// take first two elements corresponding to the Most Sign. Bits
// convert char to int, by -'0', multiply the first by 10 and sum the second
int totalsum = int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
// if the third element greater the five, increment the sum by one
if (truncatedValue[2]>=5) totalsum++;
return totalsum;
}
Any advice to make it less ugly will be deeply appreciated.
You can use fixed point integer arithmetics which are probably faster and look better. You want the number in a scale of 10^2 and you have it in an arbitrary scale power of 10 as well, so to round you just need to apply the formula:
ROUNDED_VAL = (INITIAL_VAL + (10^(ORIG_SCALE - 2) / 2)) / 10^(ORIG_SCALE - 2)
So your code could look something like this:
int roundUpto2digit(int cents){
int scale = 10;
while(cents / scale > 0) {
// Find out original scale. This can be done maybe faster with a divide and conquer algorithm
scale *= 10;
}
int applied_scale = scale / 100;
if (applied_scale == 0) {
// In case there is only one digit, scale it up to two
return 10 * cents;
}
return ((cents + (applied_scale / 2)) / applied_scale);
}
EDIT: The 10 * cents line I wrote was an arbitrary extrapolation of the problem I made based on my interpretation. If that is not the desired behavior, it can be of course changed.
#include <math.h>
int roundUpto2digit(int value)
{
value /= pow(10,(int)log10(value)-2);
/*
(int)log10(value) returns base ten logarithm (number of digits of your number)
pow(10, N) returns number 1 followed by N zeros
example:
pow(10,(int)log10(123)-2) returns 1
pow(10,(int)log10(1234)-2) returns 10
pow(10,(int)log10(1234567)-2) returns 10000
thus
value / pow(10,(int)log10(value)-2) returns first 3 digits
*/
return value%10>=5? (value+10)/10 : value/10;
/*
if(value%10>=5)// the last digit is >= 5
{
// increase previous number
value = value + 10;
}
// return number without the last digit
return value/10;
*/
}
I have used reverse code in one of the program, I donot want to actually output the reverse in my program. I want to store that reverse integer so that i can use it somewhere else too.
This is my code of reversing an integer, please tell me how to store this reverse in seperate integer . Without using character array.
This is my some piece of code
int integer;
int rev;
do{
rev=integer%10;
integer=integer/10;
cout<<rev;
}while(integer!=0);
Here's a code snippet:
int integer = 123456789;
int rev = 0;
while (integer!=0) {
rev = (10 * rev) // move all digits one to the left: 98 --> 980
+ (integer % 10); // add rightmost digit from input 980 --> 987
integer /= 10; // delete rightmost digit 1234567 --> 123456
}
printf("%d", rev);
So I've made this function on an AVR microcontroller that works OKish, but when I call
display(1)
the value shown on the 4 digit display is "1.099" instead of "1.000".
void display(float n) {
int8_t i, digit_pos=0;
unsigned short digit;
PORTC &= ~((1<<MUX_A2) | (1<<MUX_B2) | (1<<MUX_E2));
ENABLE_DISPLAY;
for (i=3;i>=-3;i--)
{
digit = n/pow(10,i);
digit = digit%10;
if (digit==0&&i>0&&digit_pos==0)
continue;
if (digit_pos-i<3)
if (i==0)
digit += 10;
PORTD = SegCode[digit];
PORTC = ((PORTC & (~(3<<MUX_A2))) | (digit_pos<<MUX_A2)) & ~(1<<MUX_E2);
PORTC |= (1<<MUX_E2);
if (digit_pos==3)
break;
else
digit_pos++;
}
PORTD=0x00;
}
The "n" variable, which is supposed to be shown, is a float, so why is the precision lost starting with the second decimal during
digit = n/pow(10,i);
digit = digit%10;
Is it because of type conversion? Is it because of some 8bit RISC processor limitation?
It's because of type conversion.
float is not precise, so when you do 1/.01 and 1/.001 in floating point, you get slightly less than 100 and 1000. (I didn't want to trace your code all that thoroughly, but that is where the problem lies.) This is rounded down to 99 and 999, which is why the 9s show up in the output.
You would be much better off to work in integers, if you can. Prevent rounding down by adding half the value of the last expected digit.
It seems like you are expecting values between 0.001 and 9999. A quick implementation would use cases:
if (n > 9999) error
else if (n >= 1000) {dec = (int)(n + 0.5); shift = 0;}
else if (n >= 100) {dec = (int)(10*(n + 0.05)); shift = 1;}
and so on
then do stuff with dec
Another tip, you don't need to use the % operator. Compute the digits from the right and store them before displaying.
dec_next = dec / 10;
digit = dec - 10*dec_next;
dec = dec_next;
digit is declared as an unsigned short, so any decimal value assigned to it will be truncated. The division you are doing yields a float value which you are trying to store in digit, so it will be truncated to be stored as an unsigned short.
You will probably want to change the type of digit to a float if you can spare the space.
sorry for the stupid question, but how would I go about figuring out, mathematically or using c++, how many bytes it would take to store an integer.
If you mean from an information theory point of view, then the easy answer is:
log(number) / log(2)
(It doesn't matter if those are natural, binary, or common logarithms, because of the division by log(2), which calculates the logarithm with base 2.)
This reports the number of bits necessary to store your number.
If you're interested in how much memory is required for the efficient or usual encoding of your number in a specific language or environment, you'll need to do some research. :)
The typical C and C++ ranges for integers are:
char 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
If you're interested in arbitrary-sized integers, special libraries are available, and every library will have its own internal storage mechanism, but they'll typically store numbers via 4- or 8- byte chunks up to the size of the number.
You could find the first power of 2 that's larger than your number, and divide that power by 8, then round the number up to the nearest integer. So for 1000, the power of 2 is 1024 or 2^10; divide 10 by 8 to get 1.25, and round up to 2. You need two bytes to hold 1000!
If you mean "how large is an int" then sizeof(int) is the answer.
If you mean "how small a type can I use to store values of this magnitude" then that's a bit more complex. If you already have the value in integer form, then presumably it fits in 4, 3, 2, or 1 bytes. For unsigned values, if it's 16777216 or over you need 4 bytes, 65536-16777216 requires 3 bytes, 256-65535 needs 2, and 0-255 fits in 1 byte. The formula for this comes from the fact that each byte can hold 8 bits, and each bit holds 2 digits, so 1 byte holds 2^8 values, ie. 256 (but starting at 0, so 0-255). 2 bytes therefore holds 2^16 values, ie. 65536, and so on.
You can generalise that beyond the normal 4 bytes used for a typical int if you like. If you need to accommodate signed integers as well as unsigned, bear in mind that 1 bit is effectively used to store whether it is positive or negative, so the magnitude is 1 power of 2 less.
You can calculate the number of bits you need iteratively from an integer by dividing it by two and discarding the remainder. Each division you can make and still have a non-zero value means you have one more bit of data in use - and every 8 bits you're using means 1 byte.
A quick way of calculating this is to use the shift right function and compare the result against zero.
int value = 23534; // or whatever
int bits = 0;
while (value)
{
value >> 1;
++bits;
}
std::cout << "Bits used = " << bits << std::endl;
std::cout << "Bytes used = " << (bits / 8) + 1 << std::endl;
This is basically the same question as "how many binary digits would it take to store a number x?" All you need is the logarithm.
A n-bit integer can store numbers up to 2n-1. So, given a number x, ceil(log2 x) gets you the number of digits you need.
It's exactly the same thing as figuring out how many decimal digits you need to write a number by hand. For example, log10 123456 = 5.09151220... , so ceil( log10(123456) ) = 6, six digits.
Since nobody put up the simplest code that works yet, I mind as well do it:
unsigned int get_number_of_bytes_needed(unsigned int N) {
unsigned int bytes = 0;
while(N) {
N >>= 8;
++bytes;
};
return bytes;
};
assuming sizeof(long int) = 4.
int nbytes( long int x )
{
unsigned long int n = (unsigned long int) x;
if (n <= 0xFFFF)
{
if (n <= 0xFF) return 1;
else return 2;
}
else
{
if (n <= 0xFFFFFF) return 3;
else return 4;
}
}
The shortest code way to do this is as follows:
int bytes = (int)Math.Log(num, 256) + 1;
The code is small enough to be inlined, which helps offset the "slow" FP code. Also, there are no branches, which can be expensive.
Try this code:
// works for num >= 0
int numberOfBytesForNumber(int num) {
if (num < 0)
return 0;
else if (num == 0)
return 1;
else if (num > 0) {
int n = 0;
while (num != 0) {
num >>= 8;
n++;
}
return n;
}
}
/**
* assumes i is non-negative.
* note that this returns 0 for 0, when perhaps it should be special cased?
*/
int numberOfBytesForNumber(int i) {
int bytes = 0;
int div = 1;
while(i / div) {
bytes++;
div *= 256;
}
if(i % 8 == 0) return bytes;
return bytes + 1;
}
This code runs at 447 million tests / sec on my laptop where i = 1 to 1E9. i is a signed int:
n = (i > 0xffffff || i < 0) ? 4 : (i < 0xffff) ? (i < 0xff) ? 1 : 2 : 3;
Python example: no logs or exponents, just bit shift.
Note: 0 counts as 0 bits and only positive ints are valid.
def bits(num):
"""Return the number of bits required to hold a int value."""
if not isinstance(num, int):
raise TypeError("Argument must be of type int.")
if num < 0:
raise ValueError("Argument cannot be less than 0.")
for i in count(start=0):
if num == 0:
return i
num = num >> 1