Getting wrong results after simple multiplication - C++ - c++

So, what needs to be done is: enter a real number and print the sum of its first 4 digits after the decimal point. E.g.: I enter 5.1010. I get to the point where I need to multiply 0.1010 by 10000 so it can become an integer, but the result I'm getting is 1009 instead of 1010 and everything falls apart after that.
I'd be forever thankful if someone can explain to me why does that happen.
#include<iostream>
using namespace std;
int main()
{
double n;
cout<<"Enter a positive real number: ";
do
{
cin>>n;
if(n<=0) cout<<"The number must be positive, enter again: ";
}while(n<=0);
//storing the fractional part in a var
int y=n;
double fr=n-y;
//turning the fractional part into an integer
int fr_int=fr*10000;
cout<<fr_int<<endl;
//storing each of the digits in a var
int a=fr_int/1000;
int b=fr_int/100%10;
int c=fr_int/10%10;
int d=fr_int%10;
cout<<"The sum of the first 4 digits is: " << a+b+c+d;
return 0;
}

You could simply change the code as follows, then it should be working.
n *= 10000;
int Integer = n;
int i = 4;
int sum = 0;
while(i--)
{
sum += (Integer%10);
Integer /= 10;
}
std::cout << "The sum of the first 4 digits is: " << sum;
Here is the output: https://www.ideone.com/PevZgn
Update:A generalized soln would be using std::string. However, would be great if the code is capable of handling exceptions in the case of non-numeric has been submitted by the user.
#include <iostream>
#include <string>
int main()
{
std::string Number;
double tempNum = 0.0;
std::cout << "Enter a positive real number: ";
do
{
std::cin >> Number;
tempNum = std::stof(Number);
if(tempNum <= 0)
std::cout << "The number must be positive, enter again: ";
}while(tempNum <= 0);
bool Okay = false;
int sum = 0;
int i = 4;
for(const auto& it: Number)
{
if(Okay && i > 0)
{
sum += static_cast<int>(it - '0');
--i;
}
if(it == '.') Okay = true;
}
std::cout << "The sum of the first 4 digits is: " << sum;
return 0;
}

I think you should add 0.5 before casting because the compile will always truncate the number.
In C++11 you can use std::round.

Floating points and doubles in C++ aren't able to represent all decimal numbers accurately. In particular, 0.1, it cannot represent faithfully.
If you must be guaranteed that you get accurate results, you should either use fixed point math or a bignumber library.

Related

Count the number of digits in a given number [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 11 months ago.
Hello I am trying to count the number of digits in a given double. I am encountering an infinite loop doing so. I tried to isolate each while statement and it works fine but when I combine them I am having an infinite loop on a the second while condition. here's the code
#include <iostream>
using namespace std;
int main()
{
//Counting digits of a number
double N, M, b;
int i, j, a;
cout << "This program will count how many digits the given whole number has.\n\n";
cout << "Please enter the Number: "; // N = 123.567 Digits should be = 6
cin >> N;
a = (int)N;
M = N - a;
b = M - int(M);
j = 0;
if (a == 0 && b == 0)
cout << "You have entered number 0.";
else
{
i = 0;
j = 0;
while (a > 0) //for the integer (whole number) part of the number
{
a /= 10;
i++;
}
while (b != 0) //for the fractional part of the number
{
j++;
M *= 10;
b = M - int(M);
}
cout << "Display i: " << i << endl; // i = number of whole number digits
cout << "Display j: " << j << endl; // j = number of fractional digits
}
system("pause > 0");
}
As a double stores fraction parts to a more significant extent, you cannot count digits in a double in this way.
Instead,
Accept the number as a string.
Convert it to double using stod()
Step2 is to make sure the user has entered the number as if it's other than the number it'll give an exception.
Count digits in the string.
Here is what it will look like
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string str = "";
cin>>str;
int counter =0;
try{
double d = stod(str);
for(int i=0;i<str.length();i++){
if(str.at(i) >= '0' && str.at(i) <= '9')
counter++;
}
cout<<counter;
}
catch(...){
cout<<"Please enter only numbers";
}
return 0;
}
I have used catch which is general, meaning it will catch all exceptions. You can use specific exception too.
Using a floating point type at any point in this analysis is not the correct thing to do. That's because (like an integral type) they can only store a subset of the real number set.
A good approach here would be to read the input as a string, check that it is a plausible number (e.g. does it contain only one decimal separator)? Write something clever to trim any zeros after the decimal separator and leading zeros before the number, allow for a negative sign, then count the digits.

How to reverse my input including the negative

This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}
You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.
After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-
I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.
Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}
If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs. The code here prints only first four digits of the binary conversion and if the number if with more than 4 digits, it shows '...' after it. On execution it hangs. Help!
#include <iostream>
using namespace std;
int main()
{
int i, x[10];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<=1)
{
i=1;
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
if (i>4)
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
cout << "...";
}
else
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
}
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
The first obstacle is the infinite while loop:
Assuming input num=0.5
after first iteration, i=1, x[0]=1, num=0.0
after second iteration, i=2, x[1]=0, num=0.0
Continue forever, i=..., x[i-]1=0, num=0.0
With nothing to break the loop.
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
To fix, consider few changes. There might be other issues.
put a limit on the while loop (i<10 should be a good condition, as this is the size of the x array), or i=4, as this is the maximum output.
The break condition for the while loop should probably be 'num != 0', or even better (num > 1e-7, or other small value).
float has 23 bit in mantissa, maybe it is because you are assign x[i] with i greater than 9.
try this:
//stop when you get four bits
while (i< 5)
Original code has several issues:
1 For input num=.5 and similar (really for all values) cycle never ends (dash-o suggested fix ideas)
2 array x[10] is overflowed with undefined behavior (Edney)
3 nitpicking: 1 is not a “fraction” and better check for a range 0 <= num < 1 instead of 0 <= num <= 1(see also OP printing code; 1 could be added); we could use x[4] with 0<=i <=3
4 string could also be used (PaulMcKenzie). Really “>>” uses string processing for parsing and calculating binary equivalent from which by multiplying by 2 (left shit) and truncation fractional part the code calculates target bits. Both approaches give correct identical results; implementing by string we need to add internal to operator “>>” implementation code to parsing valid formats for floats (decimals) such as 3.14e-1, .2718, 1e-1, etc.
This fix follows OP:
#include <iostream>
using namespace std;
int main()
{
int i, x[5];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<1)
{
i=1;
while (i<=4)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
if (num>0)
cout << "...";
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
This code is without cycles (they are in code implementing “>>”, bitset):
#include <iostream>
#include <bitset>
using namespace std;
int main () {
const int digits = 4;
int fraction;
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num >= 0 && num < 1) {
fraction = num = num * pow (2, digits);
cout << "The binary equivalent is 0.";
cout << bitset<digits> (fraction);
if (num - fraction > 0) cout << "...";
}
else cout << "The number entered is out of range.";
}

Trying to rewrite a code to include the modulus operator

The problem is as follows:
Input is the "t" number of data sets, followed by t 11-digit numbers. There's a cipher included in the code as an array. The code is supposed to multiply the subsequent digits from the input number by the corresponding digits from the cipher, thus creating a sum of 11 multiplications. After that the code checks whether the sum is divisible by 10. If so, it returns "correct", if not - "incorrect".
I've written a code which works as intended, but I'd like to simplify this code, specifically to include the modulus operator instead of fmod to extract the digits from the 11-digit input numbers. I've tried using modulus, but it can only be utilized for an int.
I found a code for a simple reversed order digit extractor (using the while loop and %10), but I'm having some trouble implementing it in my code... Any help would be appreciated.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int number;
int cipher [11] = {1,3,7,9,1,3,7,9,1,3,1};
int t, digit, sum;
cin >> t;
for (int i=0; i<t; i++)
{
sum = 0;
cin >> number;
for (int j=10; j>=0; j--)
{
digit = fmod(number/(pow(10,(10-j))),10);
sum = sum + digit*cipher[j];
}
if (sum%10==0)
cout << "Correct" << endl;
else
cout << "Incorrect" << endl;
}
return 0;
}
An example of a correct number is 44051401458. We're assuming all the input numbers are always 11 digits.
I think this is what you are referring to. You can just keep dividing number by 10, which will shift the decimal point. It will not turn into a float since you defined number as an int (long long int), so any decimal point just gets erased and you can use modulus freely.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int number;
int cipher [11] = {1,3,7,9,1,3,7,9,1,3,1};
int t, digit, sum;
cin >> t;
for (int i=0; i<t; i++)
{
sum = 0;
cin >> number;
for (int j=10; j>=0; j--)
{
digit = number%10;
number = number/10;
sum = sum + digit*cipher[j];
}
if (sum%10==0)
cout << "Correct" << endl;
else
cout << "Incorrect" << endl;
}
return 0;
}

Raise X to the power of N. Code not working for negative exponents

I'm working on a code which must calculate a Base to the power of an Exponent. Code seems to be correct if i input whatever Base and a non-negative Exponent.
The code is the following:
#include <iostream>
using namespace std;
int n; //The Exponent
int x; //The Base
double result;
int main(){
pleaseInput:
cout << "Enter Base: ";
cin >> x;
cout << "Now enter Exponent: ";
cin >> n;
//If the base is 0 could be tricky...
if(x==0){
if(n==0){
//0 ^ 0 = 1
result = 1;
}else if(n>0){
//0 ^ 3 = 0
result = 0;
}else if(n<0){
//0 ^ -2 is undefined.
cout << "0 to the power of a negative exponent is an undefined math operation. Please enter valid data. " << endl;
goto pleaseInput;
}
//If the base is other than 0...
}else{
//If the exponent is not 0...
if(n!=0){
//Make the exponent unsigned to know the amoun of iterations regardless its sign.
unsigned int exp = (unsigned int)n;
result = 1;
for(int i=0;i<exp;i++){
result *= x;
}
//If the exponent was negative...
if(n<0){
result = 1/result;
}
//If X^0....
}else{
result = 1;
}
cout << x <<" to the power of "<< n <<" equals "<< result << endl;
}
}
Please could you guys take a look and help me find where is the mistake?
Thanks a lot in advance!!
Guillermo.
First of all, excuse me if i'm not doing it properly, but it's my first time.
In the code on the OP, there was a statement:
unsigned int exp = (unsigned int)n;
I used it in order to remove the possible '-' sign from the exponent to iterate through the loop as many times as needed.
#RichardCritten told me that this line wasn't doing what I expected, and I finally realized that the way to do this was:
unsigned int exp = abs(n);
Thanks everyone for your help!