Casting in c++ not working as expected - c++

This small program is made to figure out the first and second digits of a 2 digit number. However, when I try using it on the number 99 then it prints 9 and 8, but other 2 digit numbers seem to work fine though. This is probably trivial, but I'm relatively new at programming.
#include <iostream>
using namespace std;
void test(int num) {
float numValue = (num*1.0) / 10;
cout << numValue << endl;
// prints 9.9
int firstDigit = num / 10;
cout << firstDigit << endl;
// prints 9
int secondDigit = (numValue - firstDigit) * 10;
cout << secondDigit << endl;
// prints 8, supposed to be (9.9 - 9) * 10
}
int main()
{
test(99);
return 0;
}

That happens because (numValue - firstDigit) is not exactly 0.9, but rather 0.89999..., because floating-point numbers are not accurate generally. So when you multiply 0.8999... by 10, you get the result of 8.999... However, then you are putting it into an int variable, so it gets trimmed and becomes exactly 8.
You don't really need floating point arithmetic for your exact task though, using integers will be enough.

Related

C++: Unwanted Number Added to Output

I'm writing a C++ program that converts a decimal number to binary and hexadecimal.
The problem is that for some reason it concatenates the number "1875954912" to both representations every time.
I've tried a bunch of things - mainly changing up how the program calculates numArrayLength and the for-loop in my decToBase function, but I haven't been able to figure out why this happens yet.
The program is not complete by the way - it doesn't turn integers bigger than 9 into letters for the hex representation yet, but that's not my main concern right now.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int howManyBitsNeeded(int someNum, int base) {
int numOfDivisions = 0;
while (someNum != 0) {
someNum = floor(someNum / base);
numOfDivisions += 1;
}
return numOfDivisions;
}
int decToBase(int someNum, int base) {
int bitsNeeded = howManyBitsNeeded(someNum,base);
int numArrayLength = bitsNeeded;
int numArray[bitsNeeded];
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
someNum = floor(someNum / base);
bitsNeeded -= 1;
}
for (int k = (numArrayLength-1); k >= 0; --k) {
cout << numArray[(numArrayLength - k)];
}
}
int main() {
int inpNum;
cout << "Enter your number: ";
cin >> inpNum;
cout << "Binary representation: " << decToBase(inpNum,2) << endl;
cout << "Hexadecimal representation: " << decToBase(inpNum,16);
return 0;
}
And here's what the output looks like:
Enter your number: 25
Binary representation: 110011875954912
Hexadecimal representation: 191875954912
Any help would be greatly appreciated!
Your decToBase is declared as returning an int, but it doesn't actually return anything. Your compiler should warn you about this. Since you're not returning anything here, change its return type to void. Then instead of trying to print its return value, simply call the function without printing it:
std::cout << "Binary representation: ";
decToBase(inpNum, 2); // this already prints the number, no need to pass it to std::cout
std::cout << endl;
std::cout << "Hexadecimal representation: ";
decToBase(inpNum, 16);
std::cout << std::endl;
Or of course you can change the function to return the string that you want to print instead of printing it inside the function.
Also, there's an issue here:
int numArray[bitsNeeded];
This is out of range when you try to access it here:
while (bitsNeeded > 0) {
numArray[bitsNeeded] = (someNum % base);
And also later when you try to print it. To get rid of this off by one error, you have to change this to
numArray[bitsNeeded-1] = (someNum % base);
And in the output change it to
cout << numArray[(numArrayLength - k -1)];
And while you're at it, instead of having it as a VLA (which isn't part of C++ and only works if the compiler tolerates it), I would recommend a vector:
std::vector<int> numArray(bitsNeeded+1); // include <vector> for this to work
Furthermore, note that integer division is already truncated, so unless you plan to support negative numbers later on, you can silence a warning about implicit double to int conversion by changing this:
someNum = floor(someNum / base);
To this:
someNum /= base;

get confused by mutlibly by 10 and then divide by 10

I am confused a little bit as when I multiply an int variable by 10 and then divide it by 10 I thought the variable value should not be changed but I get a different result am I missing something or there is something I should know
here is the code
#include <iostream>
using namespace std;
int main()
{
int intVar = 1500000000; //1,500,000,000
intVar = (intVar * 10) / 10; //result too large
cout << “intVar = “ << intVar << endl; //wrong answer
return 0 ;
}
any help to explain that, please
The range of a 32-bit int is -(1 << 32) to (1 << 32) - 1.
When 1.5 billion gets multiplied by ten, it exceeds the upper limit on int (which is about 2.1 billion) and overflows to a different number, and when that gets divided by 10, you get the result of that [new] number divided by ten.

c++ trying to figure out logarithms calculations

So if I am understanding c++ and logarithms correctly. Something like this should give me the base that I am looking for?
I am having some issues, but think that this way is a correct start.
#include <iostream>
using namespace std;
int main(void)
{
int x = 2;
int y = 64;
int value = log x (y);
cout << value << endl;
return 0;
}
This should display "6", but I am not sure how to really use the logarithm library..
There are three parts of a logarithm problem. The base, the argument (also called power) and the answer. You are trying to find the number of times 2 (the base) must be multiplied to get 64 (the answer).
So instead of dealing with powers and guessing. Let's just count the number of times we divide the answer 64, by the base, until we get 1.
64 / 2 = 32
32 / 2 = 16
16 / 2 = 8
8 / 2 = 4
4 / 2 = 2
2 / 2 = 1
Here we count 6 lines, so you divided the answer 64, by the base 2, 6 times. This is the same as saying you raised 2 to the 6th power to get 64.
Hmm for that to work you would need the math.h library. If you want to do this without it. You could do a loop where you constantly divide by the base given by the user.
int base = 0;
int answer = 0;
int exponent = 0;
cout << "Please type in your base";
cin >> base;
cout << "Please type in your answer";
cin >> answer;
while (answer != 1)
{
answer /= base;
exponent++
}
cout << "The exponent is " << exponent;
The implementation of a logarithm is most times a tayler function with approximates logarithm to the base e. To get the logarithm to any other base you do something like this:
#include <cmath>
double y = std::log(x)/std::log(base);
Description:
std::log() natural logarithm to base e.
y = result
base = base of the logarithm. Like 2 or 10.
For your reference:
http://en.cppreference.com/w/cpp/numeric/math/log
http://en.cppreference.com/w/c/numeric/math/log
https://en.wikipedia.org/wiki/Logarithm
https://en.wikipedia.org/wiki/Logarithm#Change_of_base
https://en.wikipedia.org/wiki/Taylor_series
https://en.wikipedia.org/wiki/Taylor_series#Examples
Here's a better implementation without using the math.h library. I might have some superfluous code as it's been like a year since I have written in C++. (Shame on me) Thanks for your question it got me wanting to brush up on my C++!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float base = 0;
float answer = 0;
int exponent = 0;
cout.precision(4);
cout << "Please type in your base \n";
cin >> base;
cout << "Please type in your answer\n";
cin >> answer;
cout << fixed;
while (answer > base)
{
answer /= base;
exponent++;
}
cout << "The exponent is: " << exponent << endl;
cout << "The Remainder is: " << fixed << answer << endl;
return 0;
}

How to work with Base 8 (Octal) numbers?

In C++, an octal number is defined by preceeding it with a 0, example:
01 = 1
010 = 8
014 = 12
So I was experimenting how working with Base 8 in c++ works, and tried adding to it with a loop, like so:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << base8Number << '\n';
}
And apparently, C++ doesn't like working with octal numbers, the output I got is as follows:
1
3
6
10
15
21
28
36
The most obvious reason I know it's not working in Base 8, is the 28 output as a result, since the 8 number isn't used in Base 8.
So, my question: Can you work with Base 8 in c++, or is it just meant to be used as a constant, and if you can work with Base 8 in c++, how do you do it?
So first, let's remember that when we print numbers the way you're doing, they will be shown in decimal.
Now, let's rewrite your code without octal:
int base10Number = 0;
for (int i = 1; i < 9; i+=1)
{
base10Number += i;
cout << base10Number << '\n';
}
So let's now look at what your code is actually doing:
cout << 1 << "\n"; // 1
cout << 1 + 2 << "\n"; // 3
cout << 1 + 2 + 3 << "\n"; // 6
cout << 1 + 2 + 3 + 4 << "\n"; // 10
....
Which is what you're seeing. So no, there is no problem with how octal works in c++.
If you'd like you can use std::oct to tell std::cout to use octal printing. For example:
int main() {
std::cout << std::oct << 25 << "\n"; // Outputs: 31
}
Remember that "base" is a property of number representation, not the number itself. If you've got enough pegs to put one on each finger, then that is the same number of pegs regardless of whether you write 10, 012 0xA, or anything else.
Your code computes the numbers which would be shown in base 10 as 1, 3, 6, 10, 15, etc. You output them in base 10. To output them in base 8 use:
std::cout << std::oct << base8Number << std::endl;
There are a couple of things going on here.
Intrinsically, your computer operates in binary (base 2). When you do something like int foo = 10;, you are expressing the number 10 in decimal form because it's convenient for you to read it that way, but in the end the computer will still store it using binary, e.g. 1010.
If you were to use an octal literal (e.g. 012), then as far as the computer's concerned that's still just a 1010 binary constant - the only thing that's changed is its representation in the source code.
Finally, the last thing to realise is that the computer will by default output integers in base 10, because that's what's easy for people to read. It's still outputting the number 1010, just using the decimal representation of it.
Given all of the above, your code is entirely equivalent to doing the following, which you can verify for yourself produces the same output without using any octal:
int num = 0;
for (int i = 1; i < 9; i += 1) // Constants the same, just changed from octal representation to decimal.
{
num += i;
cout << num << '\n'; // Outputs in decimal, as with original program.
}
To get what you expect, try using the oct modifier:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << oct << base8Number << '\n';
// ^--Here. Explicitly requests octal output.
}
This then explicitly requests that the computer output the values using octal.

C++ Long Division

Whilst working on a personal project of mine, I came across a need to divide two very large arbitrary numbers (each number having roughly 100 digits).
So i wrote out the very basic code for division (i.e., answer = a/b, where a and b are imputed by the user)and quickly discovered that it only has a precision of 16 digits! It may be obvious at this point that Im not a coder!
So i searched the internet and found a code that, as far as i can tell, uses the traditional method of long division by making a string(but too be honest im not sure as im quite confused by it). But upon running the code it gives out some incorrect answers and wont work at all if a>b.
Im not even sure if there's a better way to solve this problem than the method in the code below!? Maybe there's a simpler code??
So basically i need help to write a code, in C++, to divide two very large numbers.
Any help or suggestions are greatly appreciated!
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char **argv)
{
string dividend, divisor, difference, a, b, s, tempstring = ""; // a and b used to store dividend and divisor.
int quotient, inta, intb, diff, tempint = 0;
char d;
quotient = 0;
cout << "Enter the dividend? "; //larger number (on top)
cin >> a;
cout << "Enter the divisor? "; //smaller number (on bottom)
cin >> b;
//making the strings the same length by adding 0's to the beggining of string.
while (a.length() < b.length()) a = '0'+a; // a has less digits than b add 0's
while (b.length() < a.length()) b = '0'+b; // b has less digits than a add 0's
inta = a[0]-'0'; // getting first digit in both strings
intb = b[0]-'0';
//if a<b print remainder out (a) and return 0
if (inta < intb)
{
cout << "Quotient: 0 " << endl << "Remainder: " << a << endl;
}
else
{
a = '0'+a;
b = '0'+b;
diff = intb;
//s = b;
// while ( s >= b )
do
{
for (int i = a.length()-1; i>=0; i--) // do subtraction until end of string
{
inta = a[i]-'0'; // converting ascii to int, used for munipulation
intb = b[i]-'0';
if (inta < intb) // borrow if needed
{
a[i-1]--; //borrow from next digit
a[i] += 10;
}
diff = a[i] - b[i];
char d = diff+'0';
s = d + s; //this + is appending two strings, not performing addition.
}
quotient++;
a = s;
// strcpy (a, s);
}
while (s >= b); // fails after dividing 3 x's
cout << "s string: " << s << endl;
cout << "a string: " << a << endl;
cout << "Quotient: " << quotient << endl;
//cout << "Remainder: " << s << endl;
}
system ("pause");
return 0;
cin.get(); // allows the user to enter variable without instantly ending the program
cin.get(); // allows the user to enter variable without instantly ending the program
}
There are much better methods than that. This subtractive method is arbitrarily slow for large dividends and small divisors. The canonical method is given as Algorithm D in Knuth, D.E., The Art of Computer Programming, volume 2, but I'm sure you will find it online. I'd be astonished if it wasn't in Wikipedia somewhere.