Could anyone please tell me how to check what number I've got from a * b? Which is I would like to know every part of this number so for example if the result from this expression would be 25 I would like to know that first digit is two and second digit is five.
perhaps a little overkill... but even works with doubles
#include <sstream>
#include <iostream>
int main()
{
double a = 5.2;
double b = 7;
double z = a*b;
std::stringstream s;
s << z;
for (int i = 0; i < s.str().length(); i++)
std::cout << i << ": " << s.str()[i] << std::endl;
return 0;
}
a mod 10 == last digit of a
a / 10 == a without its last digit
So, for 25:
25 % 10 == 5 => 5 is the last digit of 25
25 / 10 == 2
2 % 10 == 2 => 2 is the first digit of 25
You can use these in a while loop to get each digit.
while (num > 0)
{
digit = num % 10;
// digit is now the current digit, counting from the right towards the left.
num /= 10;
}
int val = res;
while( val > 0 )
{
std::cout << val % 10 << endl;
val /= 10;
}
You have to get the result of the integer division by the appropriate power of ten.
int exp = std::floor( std::log10( num ) );
int first_digit = num / int( std::pow( 10.0, exp ) );
This is an (inefficient) way to get the first digit directly. It would be better to iterate starting from the last.
char str[30];
sprintf(str,"%d",a*b);
int ndigits = strlen(str);
There you have all digits of your value in the string, and the number of digits in ndigits.
e.g. if a*b = 25 you get
ndigits==2
str[ndigits-1]=='5'
str[ndigits-2]=='2'
What do you want this for?
There's probably an underlying misunderstanding here. The result of the multiplication will most likely be 0x00000019. (Number of leading zeroes will differ). The second step, converting it to canonical decimal will yield "25".
It's important to realize that computers, unlike normal humans, don't do their math in decimal but in binary. Hence, if you want to check a property like "last decimal digit of a number", it's not directly available to them.
Just remember, that e.g. 2101 is basically just 2*10^3 + 1*10^2 + 0*10^1 + 1*10^0.
Related
this is a super simple problem but it's late and I cant figure out for the life of me why this function doesnt work. I want it to print 1234, but instead it prints 123121. can someone explain what's going on and how to fix it? thanks
#include <iostream>
const int size = 20;
void set_int( int num )
{
int digits[size];
for ( int i = size - 1; i >= 0; i-- )
{
digits[i] = num % 10;
num /= 10;
if ( num != 0 )
std::cout << num;
}
}
int main()
{
set_int( 1234 );
return 0;
}
Well you are outputting the number instead of the digit.
Try changing like,
cout << digits[i]
Further clarification :
On the first run of the loop your num will be 1234 / 10 = 123
Next run your number will be 123 / 10 = 12
Next is going to be 1
You are outputing num, so you get 123121 .
There are several things wrong with that code.
Firstly, the definition
int digits[size];
is a variable length array, which is valid C (since the 1999 C standard) but is not valid C++. Unfortunately, some C++ compilers support such things as an extension.
Second, even if we assume that definition is valid, your code is essentially stating that you need an array with 1234 elements to hold integral values corresponding to four digits (1,2,3, and 4).
As MichaelCMS has described, your code is outputting something other than the digits too. A value of 1234 has 4 digits, so you would need to loop a total of 4 times to find all digits (if doing it right). You would not need to loop 1234 times.
MichaelCMS explained correctly, why you have such output. There are mistakes in your function. I wrote another one.
You can use next code, which helps to find digits of number.
#include <iostream>
int FindNumberOfDigits(int number);
void SplitNumberIntoDigits(int number);
// Splits number into digits.
// Works with not big numbers.
void SplitNumberIntoDigits(int number)
{
int size = FindNumberOfDigits(number);
int * digits = new int[size];
int divider = 0;
int degree = 0;
for(int digit = size; digit > 0; digit --)
{
// Find degree of divider
degree = digit;
// Find divider for each digit of number.
// For 1234 it will be 1000. For 234 it will be 100.
divider = pow(10, degree - 1);
// We use "abs" to get digits without "-".
// For example, when -1234 / 1000, you get -1.
digits[digit] = abs(number / divider);
// Cut number to find remaining digits.
number %= divider;
std::cout << digits[digit];
}
std::cout << std::endl;
}
// If number = 0, number of digits will be 1.
// Else returns number of digits.
int FindNumberOfDigits(int number)
{
int digitsNumber = 0;
if (number)
{
// calculates number of digits
while (number / 10)
{
number /= 10;
digitsNumber ++;
}
}
digitsNumber += 1;
return digitsNumber;
}
int _tmain(int argc, _TCHAR* argv[])
{
SplitNumberIntoDigits(1234);
SplitNumberIntoDigits(0);
SplitNumberIntoDigits(1);
SplitNumberIntoDigits(-1234);
SplitNumberIntoDigits(1234567890);
return 0;
}
As a result this code can help you to find digits of not big numbers. It works with positive, negative numbers and zero.
I would like to count the number of decimal digits after the radix point of a floating point number.
The problem obviously raise when the real number doesn't have a representation in the binary system, like 3.5689113.
I am wondering - if for example someone write this real in a source code - if it is possible to get the number 7 namely the number of digits after the radix point
the naive following code for example doesn't work :
int main()
{
double num = 3.5689113;
int count = 0;
num = abs(num);
num = num - int(num);
while ( abs(num) >
0.0000001 )
{
num = num * 10;
count = count + 1;
num = num - int(num);
}
std::cout << count; //48
std::cin.ignore();
}
When something like that doesn't work, you try to print the numbers.
I did so here, and I found you had some floating number precision issues.
I changed the int rounding to ceil rounding and it worked like a charm.
Try putting the ints back and you'll see :)
EDIT: a better strategy than using ceils (which can give the same rounding problems) is to just round the numbers to the nearest integer. You can do that with floor(myNumber+0.5).
Here's the modified code
int main()
{
double num = 3.56891132326923333;
// Limit to 7 digits
num = floor(num*10000000 + 0.5)/10000000;
int count = 0;
num = abs(num);
num = num - floor(num+0.5);
while ( abs(num) >
0.0000001 )
{
cout << num << endl;
num = num * 10;
count = count + 1;
num = num - floor(num+0.5);
}
std::cout << count; //48
std::cin.ignore();
return 0;
}
To prevent the errors introduced by floating point approximation, convert the number to an integer at the earliest possible opportunity and work with that.
double num = 3.5689113;
int count = 7; // a maximum of 7 places
num = abs(num);
int remainder = int(0.5 + 10000000 * (num - int(num)));
while ( remainder % 10 == 0 )
{
remainder = remainder / 10;
--count;
}
For a floating point type T you can get up to std::numeric_limits<T>::digits10 digits restored exactly. Thus, to determine the position of the last non-zero fractional digits you'd use this value as a precision and format the number. To avoid the output using exponent notation you need to set the formatting flags to std::ios_base::fixed and account for the number of non-fractional digits:
std::ostringstream out;
int non_fraction(std::abs(value) < std::numeric_limits<double>::epsilon()
? 1: (1 + std::log(std::abs(value)) / std::log(10)));
out << std::setprecision(std::numeric_limits<double>::digits10 - non_fraction)
<< std::fixed
<< value;
If there is a decimal point, you just need to count the number of digits up to the trailing sequence of zeros.
I would recommend converting to a string, then looping over it and counting how many chars occur after you hit the period. Below is a sample (may need some minor tinkering, been awhile since I've done this in C++);
bool passedRadix = false
int i = 0; // for counting decimals
std::ostringstream strs;
strs << dbl; // dbl is 3.415 or whatever you're counting
std::string str = strs.str();
for(char& c : str) {
if (passedRadix == true)
i++;
if (c == '.')
passedRadix = true;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Split an Integer into its digits c++
Given a number 4567.
In C++, how can you separately access 4, 5, 6 and 7?
The ones digit is n % 10, the tens digit is (n / 10) % 10, and so on. Be careful about negative numbers, the rules are slightly different.
Just to augment answers already here... You do long division. This gives you the least significant digits first.
n = abs(n);
while( n != 0 ) {
int r = n % 10;
n = n / 10;
cout << r << endl;
}
Output:
7
6
5
4
Obviously, this method gives you the least-significant digits first. You could of course generate that into an array so that you could access each number by its power (element 0 is 10^0, 1 is 10^1, etc...)
To go the other way, convert the number to a string. This approach will be slightly less efficient than long division. I know this question stated C++, but there's nothing wrong with using the C function itoa.
char s[33];
itoa(abs(n), s, 10);
for( char *d = s; d != 0; d++ ) {
int r = *d - '0';
cout << r << endl;
}
Output:
4
5
6
7
I'm not entirely sure about C++, but I know python at least will round always down, so to get the last digit you could use mod 10, and then divide out the last digit by 10, so, in sudo code
int num_to_test = 1234;
for (int i = 0; i < num_to_test.length; i++ ) {
print num_to_test % 10;
num_to_test = num_to_test / 10;
}
Do a little math and reduce the num as you go. Like this:
int thousands = floor(num / 1000);
num = num - thousands * 1000;
int hundreds = floor(num / 100);
num = num - hundreds * 100;
and furthermore, I hope you see where that is going.
Can you help me please? I try to do with while statement but I could not write the program.
Given an integer for example 12564897 and the program must show it 1-2-5-6-4-8-9-7
How do you detect in C++. Thanks a lot.
I tried with five digits integer.
int z,y,x,result,number1,number2,number3,number4,number5;
cout<<"Enter a five digit integer: ";
cin>>result; //read number
cout<<"The number is: "<<result<<endl;
number1 = result / 10000;
x = result / 1000;
number2 = x % 10;
y = result / 100;
number3 = y % 10;
z = result / 10;
number4 = z % 10;
number5 = result % 10;
cout<<"digits are: "<<number1<<"-"<<number2<<"-"<<number3<<"-"<<number4<<"-"<<number5<<endl;
system("pause");
return 0;
}
I think the smartest way is create a loop that divide by ten ( or the base ) and print the remainder, then divide by ten and do again. In preudo code:
let a = input
let base = 10
do
{
store a mod base in result
a = (integer) a / base;
}while(a>0)
print result reversed
mod is the remainder operator ( % in C/C++ )
please note thad by changing base you can have the digit in any representation of the number
Convert your Integer to a string and then print every character of that string with a - in between.
This is snippet from program which print out integer in reverse order.
You can modify it to fits your need (it's your homework)
//Read input number
cin >> dInput;
//Calculate log10
int logValue = (int)log10(dInput);
//Iteration through n-th power of 10
for(int i = logValue; i >= 0; i--) {
//Calculate actual power of 10
double d = pow(10,(double)i);
int n = (int)dInput / d;
//Subtract remainder from previous number
dInput -= (n * d);
//Print out "-"
cout << n;
if(i != 0) << "-";
}
I thought about writing the code itself, but since it's a homework, I'll give you the idea and let you code it
First, you'll convert that integer to a string using sprintf function
Then you'll make an integer having the size of the string. Let it be S
Then you'll make a for loop,
i=1, i < S, i+=2
i starts from 1 as the - is put after the first character
In that loop, you would insert the - character at the position of i, then you'll update integer S with the size. If you didn't update it, the following (for example) would happen
12345 (size = 5)
1-2345 (size = 5, real size = 6)
1-2-345 (size = 5, real size = 7)
It would stop here. As the condition i<5 would fail
That's all. Good luck.
OK, since everyone else has had a go, this is my attempt:
void outInt(int inInt){
int dividend;
dividend=inInt/10;
if (dividend!=0){
outInt(dividend);
cout<<"-"<<inInt%10;
}
else
cout<<(inInt);
};
No 'print result reversed' required. Should work for 0 and not print any '-' for numbers less than 10.
I wrote program to convert decimal to binary for practice purposes but i get some strange output. When doing modulo with decimal number, i get correct value but what goes in array is forward slash? I am using char array for being able to just use output with cout <<.
// web binary converter: http://mistupid.com/computers/binaryconv.htm
#include <iostream>
#include <math.h>
#include <malloc.h> // _msize
#include <climits>
#define WRITEL(x) cout << x << endl;
#define WRITE(x) cout << x;
using std::cout;
using std::endl;
using std::cin;
char * decimalToBinary(int decimal);
void decimal_to_binary_char_array();
static char * array_main;
char * decimalToBinary(int decimal) // tied to array_main
{
WRITEL("Number to convert: " << decimal << "\n");
char * binary_array;
int t = decimal, // for number of digits
digits = 0, // number of digits
bit_count = 0; // total digit number of binary number
static unsigned int array_size = 0;
if(decimal < 0) { t = decimal; t = -t; } // if number is negative, make it positive
while(t > 0) { t /= 10; digits++; } // determine number of digits
array_size = (digits * sizeof(int) * 3); // number of bytes to allocate to array_main
WRITEL("array_size in bytes: " << array_size);
array_main = new char[array_size];
int i = 0; // counter for number of binary digits
while(decimal > 0)
{
array_main[i] = (char) decimal % 2 + '0';
WRITE("decimal % 2 = " << char (decimal % 2 + '0') << " ");
WRITE(array_main[i] << " ");
decimal = decimal / 2;
WRITEL(decimal);
i++;
}
bit_count = i;
array_size = bit_count * sizeof(int) + 1;
binary_array = new char[bit_count * sizeof(int)];
for(int i=0; i<bit_count+1; i++)
binary_array[i] = array_main[bit_count-1-i];
//array_main[bit_count * sizeof(int)] = '\0';
//WRITEL("\nwhole binary_array: "); for(int i=0; i<array_size; i++) WRITE(binary_array[i]); WRITEL("\n");
delete [] array_main;
return binary_array;
}
int main(void)
{
int num1 = 3001;
// 3001 = 101110111001
// 300 = 100101100
// 1000 = 1111101000
// 1200 = 10010110000
// 1000000 = 11110100001001000000
// 200000 = 110000110101000000
array_main = decimalToBinary(num1);
WRITEL("\nMAIN: " << array_main);
cin.get();
delete [] array_main;
return 0;
}
The output:
Number to convert: 3001
array_size in bytes: 48
decimal % 2 = 1 / 1500
decimal % 2 = 0 0 750
decimal % 2 = 0 0 375
decimal % 2 = 1 1 187
decimal % 2 = 1 / 93
decimal % 2 = 1 1 46
decimal % 2 = 0 0 23
decimal % 2 = 1 1 11
decimal % 2 = 1 1 5
decimal % 2 = 1 1 2
decimal % 2 = 0 1 1
decimal % 2 = 1 1 0
MAIN: 1111101/100/
What are those forward slashes in output (1111101/100/)?
Your problem is here:
array_main[i] = (char) decimal % 2 + '0';
You are casting decimal to char and it is swiping off the high-order bits, so that in some cases it becomes negative. % applied to a negative number is negative, hence you get one character before 0 in the ASCII chart, which is /.
I would also like to say that I think your macros WRITEL and WRITE qualify as preprocessor abuse. :-)
It must be array_main[i] = (char) (decimal % 2 + '0'); (note the parentheses). But anyway, the code is horrible, please write it again from scratch.
I haven't tried to analyze all your code in detail, but just glancing at it and seeing delete [] array_main; in two places makes me suspicious. The length of the code makes me suspicious as well. Converting a number to binary should take about two or three lines of code; when I see code something like ten times that long, I tend to think that analyzing it in detail isn't worth the trouble -- if I had to do it, I'd just start over...
Edit: as to how to do the job better, my immediate reaction would be to start with something on this general order:
// warning: untested code.
std::string dec2str(unsigned input) {
std::deque<char> buffer;
while (input) {
buffer.push_front((input & 1)+'0');
input >>= 1;
}
return std::string(&buffer[0], &buffer[0]+buffer.size());
}
While I haven't tested this, it's simple enough that I'd be surprised if there were any errors above the level of simple typos (and it's short enough that there doesn't seem to be room to hide more than one or two of those, at very most).