c++ - why the result is minus? - c++

I have some problem with my simple program where if my input more than 295600127, the result is minus (-).
here :
#‎include‬ <iostream>
#include <windows.h>
using namespace std;
int konarray(int b);
void konbil(int A[], int &n);
int kali(int x);
main(){
int b;
char *awal,akhir,pil;
awal:
system("COLOR 9F");
cout<<"enter decimal\t= ";cin>>b;
//calling function of conversion to an array of integers
konarray(b);
akhir:
cout<<"\n\nDo You Want To Reply Now ? (Y/N) : ";
cin >> pil;
cout<<endl;
switch(pil){
case 'Y' :
case 'y' :
system ("cls");
goto awal;
break;
case'N':
case 'n' :
break;
default:
system("COLOR c0");
system ("cls");
cout << "Please, make sure for entering the choise!!\n\n\n\n";
goto akhir;
}
}
//convertion numer to array
int konarray(int b){
int A[30];
int i,n,h,s;
i=0;
do{
h=b/8;
s=b%8;
b=h;
A[i]=s;
i++;
}
while(h!=0);
n=i;
for(i=0;i<n;i++)
cout<<A[i]<<" ";
konbil(A,n);
}
//array to octal
void konbil(int A[],int &n){
int c,i;
c=A[0];
for(i=1;i<n;i++)
c=c+A[i]*kali(i);
system("COLOR f0");
cout<<endl<<"the results of the conversion are\t= ";
cout<<c<<endl;
}
int kali(int x){
if (x==1)
return (10);
else
return(10*kali(x-1));
}
i have tried change of all int into long, but it was same.
I want to know some reason why?
and how to fix it?

295600128 decimal is octal is 2147500000. When you try to then put 2147500000 as a decimal number into an int, it overflows the 4 byte signed limit, which gives you the negative value.
One question - why do you want to store an octal number back in a variable as a decimal number? If you just want to display the number, you already have it in A.
If you just want to display a number as octal, std::ostream can already do this:
std::cout << std::oct << b << '\n';
If for some reason you really do need a decimal representation of an octal number in an integer variable, you will need to change c and kali to long long.

Have you tried
long long int
This program
int main(int argc, char** argv)
{
cout << sizeof(int) << endl;
cout << sizeof(long int) << endl;
cout << sizeof(long long int) << endl;
return 0;
}
gives
4
4
8
showing you need long long int to get 64 bits
Change like this:
void konbil(int A[],int &n){
unsigned long long c,i; // unsigned long long
c=A[0];
for(i=1;i<n;i++)
c=c+A[i]*kali(i);
system("COLOR f0");
cout<<endl<<"the results of the conversion are\t= ";
cout<<c<<endl;
}
The largest positive number you can store int an int is 2147483647 (2^31 - 1).
Adding just 1 to that number will result in the value -2147483648 (- 2^31).
So the answer is that you have an overflow while using int.
Therefore you need long long int or even better unsigned long long.
unsigned long long can't be negative and allows the maximum value (2^64 - 1).
EDIT:
An extra question was added in the comment - therefore this edit.
int
On most systems an int is 32 bits.
It can take values from -2^31 to 2^31-1, i.e. from -2147483648 to 2147483647
unsigned int
An unsigned int is also 32 bits. However an unsigned int can not be negative.
Instead it has the range 0 to 2^32-1, i.e. from 0 to 4294967295
long long int
When you use long long int you have 64 bits.
So the valid range is -2^63 to 2^63-1, i.e. -9223372036854775808 to 9223372036854775807
unsigned long long
A unsigned long long is also 64 bits but can not be negative.
The range is 0 to 2^64-1, i.e. 0 to 18446744073709551615
Try this code:
int main()
{
cout << endl << "Testing int:" << endl;
int x = 2147483647; // max positive value
cout << x << endl;
x = x + 1; // OVERFLOW
cout << x << endl;
cout << endl << "Testing unsigned int:" << endl;
unsigned int y = 4294967295; // max positive value
cout << y << endl;
y = y + 1; // OVERFLOW
cout << y << endl;
cout << endl << "Testing long long int:" << endl;
long long int xl = 9223372036854775807LL; // max positive value
cout << xl << endl;
xl = xl + 1; // OVERFLOW
cout << xl << endl;
cout << endl << "Testing unsigned long long:" << endl;
unsigned long long yl = 18446744073709551615ULL; // max positive value
cout << yl << endl;
yl = yl + 1; // OVERFLOW
cout << yl << endl;
return 0;
}
it will give you
Testing int:
2147483647
-2147483648
Testing unsigned int:
4294967295
0
Testing long long int:
9223372036854775807
-9223372036854775808
Testing unsigned long long:
18446744073709551615
0
showing how you overflow from max positive value by adding just 1.
Also see this link http://www.cplusplus.com/reference/climits/

Related

How i can use a eleven-digit number

I want to enter a eleven-digit number in my variable - number, but I think there's not so much memory. I tried to use *number and int *number = new int[100], but it's not working.
I also want to add name and lastname in my variable - name, but everytime I use space, it's stops working too.
How I can solve these problems?
#include <iostream>
#include <string>
using namespace std;
struct NOTE {
string name;
int number;
int birthday[3];
};
int main()
{
//int *tel = new int[100];
//int *ptr = new int;
NOTE arr[3];
cout << "Please enter quality names and numbers or program stop working!";
for (int i = 0; i < 3; i++) {
cout << "Man #" << i + 1 << "\n";
cout << "Name: ";
cin >> arr[i].name;
cout << "Number: ";
//*tel = arr[i].number;
//cin >> *tel;
cin >> arr[i].number;
cout << "Year: ";
cin >> arr[i].birthday[0];
cout << "Month: ";
cin >> arr[i].birthday[1];
cout << "Day: ";
cin >> arr[i].birthday[2];
}
}
You are currently using a signed integer to hold your value.
int number;
A signed int can hold a maximum value of 2^31 (2,147,483,648‬), which is only 10 digits long.
unsigned int number;
An unsigned integer can hold 2^32 which is 4,294,967,296‬ (still 10 digits), which still isn't enough.
You can use a signed long, which is 64 bits in size and can hold a maximum of 2^63 (9,223,372,036,854,775,808), which is 19 digits long. That should suffice.
long number;

C++ calculating the ratio of 2 numbers [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed 1 year ago.
Hi guys I'm rather new to programming and working my way through Stroustrup's "Programming, Principles and Practice Using C++" and I've come to a complete standstill at the end of Chapter 3 with an exercise asking you to write a piece of code that does a number of calculations involving 2 numbers which includes finding the ratio of the numbers. Unfortunately this hasn't been covered at all in the book and I'm tearing my hair out trying to figure it out by myself, only able to find examples of code way to advanced for my small little brain.
The code I have at the moment is:
double ratio;
if (val2 > val1)
ratio = (val2 / val1);
if (val2 < val1)
ratio = (val1 / val2);
cout << "The ratio of " << val1 << " and " << val2 << " is 1:" << ratio << '\n';
which works fine for numbers that equate to a whole ratio (e.g. 100 and 25) however despite me setting the variable "ratio" as a double it removes any decimals from the answer in cases of non whole number ratios. Can anyone tell me where I'm going wrong?
When dividing integers the result is integer (integer arithmetics is used):
11 / 2 == 5
11 % 2 == 1 /* remainder */
and when dividing floating point values the result is floating point as well:
11.0 / 2 == 5.5
11 / 2.0 == 5.5
((double) 11) / 2 == 5.5
In your case
double ratio = (val2 / val1);
you have an integer division and only after the disvison performed the outcome of it is cast to double. You can either declare val2 and val1 as double:
double val1;
double val2;
or cast at least one argument of the ratio to double:
double ratio = ((double)val2) / val1;
The fact that result type is double doesn't matter if the original division is performed on integral types (truncating the decimal part).
So to solve your problem, either:
Use a floating point type for the input numbers as well
Cast one of the numbers to a floating point type before division
I did the whole problem from Stroustrup's "Programming, Principles and Practice Using C++. Here is the codes although no comments.
int main()
{
/** --------Numbers-----*/
int val1;
int val2;
double largest; //I'll store here the largest value
double smallest; //I'll store here the smallest value
cout<< " Enter two Numbers to play with\n";
while(cin>> val1>>val2){
if(val1<val2){
cout<< "smallest: "<<val1<<endl;
cout<< "largest: "<<val2<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val2;
smallest=val1;}
if(val1>val2){
cout<< "smallest: "<<val2<<endl;
cout<< "largest: "<<val1<<endl;
//If the above argument succeeds, largest and smallest will get their values
largest=val1;
smallest=val2;}
int their_sum=val1+val2;
int their_product=val1*val2;
int their_diff=val1-val2;
double ratio1;
ratio1=largest/smallest;
cout<<"Sum: "<<their_sum<<endl;
cout<<"Difference: "<<their_diff<<endl;
cout<<"Product: "<<their_product<<endl;
cout<<"Ratio: "<<ratio1;
}
return 0;
}
There is nothing new in this code, everything was covered in the previous chapters.
If at all you need ratio of two numbers say a,b in the form of n:m (where n>=1) then simply find the GCD(a,b) and divide a,b with this result.
eg:
a=4,b=6;
GCD(a,b)=2;
n=4/2=>2
m=6/2=>3
so ratio of 4 and 6 is 2:3
#include<iostream>
using namespace std;
class Test
{
public:
void check()
{
int x,y;
cout<<"Enter 1st number";
cin>>x;
cout<<"Enter 2nd number";
cin>>y;
int a;
int d= gcd(x,y);
cout<< x/d << " : " << y / d << endl;
}
int gcd(int x, int y) // 14, 21
{
int d;
if(y>x)
{
y=x+y;
x=y-x;
y=y-x;
}
for(int i=1; i<=y; i++)
{
if(x%i==0 && y%i==0 )
{
d=i;
}
}
return d;
}
};
int main()
{
Test t;
t.check();
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val1,val2;
cout << " Enter two integer values followed by enter" << endl << endl;
cin >> val1;
cin >> val2;
if(val1 < val2) // To determine which value is larger and which one is smaller
{
cout << val1 << " is smaller than" << val2 << endl << endl << "And" << val2 << " is larger than " << val1 << endl<<endl;
}
enter code here
else if( val2 < val1)
{
cout<<val2 <<" is smaller than"<< val1<<endl<<endl<<"And"<< val1 << " is larger than "<< val2<< endl << endl;
}
cout << "The sum of "<< val1<<" and "<<val2<<" is "<< val1+val2<<endl<<endl;
// diplaying the sum of the two numbers
enter code here
cout << " The difference between "<<val1<< " and "<<val2<< " is " << val1-val2<<endl;
// displays the difference of val2 from val1
cout << " The difference between "<<val2<< " and "<<val1<< " is " << val2-val1<<endl;
// displays thr difference of val1 fromval2
enter code here
enter code here
cout << " The product of " <<val1<< " and " << val2<< " is " << val1*val2<< endl<<endl;
// displaying the product of val1 and val2
enter code here
enter code here
enter code here
// now to diplay the ratio of the two numbers
double ratio1;
cout << " The ratio of "<<val1<<" and "<<val2<<" is ";
if(val1 < val2)
{
ratio1= ((double)val2) /val1;
cout << ratio1;
}
else if(val1 > val2)
{
ratio1= ((double)val1) /val2;
cout << ratio1;
}
}

Conversion base 11 to decimal

I know that the unsigned long is up to 4294967295 only, so here's my problem, when the user inputs many numbers (like the result is going to exceed on the limit) the converted number will be just 4294967295.
example:
Base 11: 1928374192847
Decimal: 4294967295
the result should be 5777758712535. how to fix this limit ? vb6.0 required to us.
here's my code:
cout << "\t\t CONVERSION\n";
cout << "\t Base 11 to Decimal\n";
cout << "\nBase 11: ";
cin >> str;
const auto x = str.find_first_not_of("0123456789aA");
if (x != string::npos)
{
std::cout << "Invalid Input\n\n";
goto a;
}
unsigned long x = strtoul(str.c_str(), NULL, 11);
cout << "Decimal: " << x << "\n\n";
The program should say "out of range" if the result will exceed 4294967295.
Sorry im just a beginner.
From the strtoul docs on www.cplusplus.com :
If the value read is out of the range of representable values by an unsigned long int, the function returns ULONG_MAX (defined in <climits>), and errno is set to ERANGE.
You should check the errno to determine if the value was out of range.

Bit representation of characters C++

Here's my program for bit representation of characters. But I don't know does it show me right or wrong representation? There are suspicious units (red colored).
Can you explain me what's this (if it's right) or what's wrong with my code if these units should not be. Thanks
#include "stdafx.h"
#include "iostream"
using namespace std;
struct byte {
unsigned int a:1;
unsigned int b:1;
unsigned int c:1;
unsigned int d:1;
unsigned int e:1;
unsigned int f:1;
unsigned int g:1;
unsigned int h:1;
};
union SYMBOL {
char letter;
struct byte bitfields;
};
int main() {
union SYMBOL ch;
cout << "Enter your char: ";
while(true) {
ch.letter = getchar();
if(ch.letter == '\n') break;
cout << "You typed: " << ch.letter << endl;
cout << "Bite form = ";
cout << ch.bitfields.h;
cout << ch.bitfields.g;
cout << ch.bitfields.f;
cout << ch.bitfields.e;
cout << ch.bitfields.d;
cout << ch.bitfields.c;
cout << ch.bitfields.b;
cout << ch.bitfields.a;
cout << endl << endl;
}
}
See the ASCII table to understand the output you're getting:
a has the decimal value of 97, and 97 is 01100001 in binary
b has the decimal value of 98, and 97 is 01100010 in binary
and so on.
Bit fields are not portable. The biggest problem is that you don't know in which order the bits will be assigned to the individual bit fields, but you don't even know actually whether the struct will have 1, 2 or any other number of bytes.
I'd recommend using unsigned char (because you don't know whether char is signed or unsigned), and using code like (ch & 0x80) != 0, (ch & 0x40) != 0 etc.

my code crashes when introducing giant numbers

i have the next code which asks the user to introduce a number larger than 100000000, and then it asks for a digit that the code must search in the number, finally the code shows how many times the digit appears on the number, it seems to be easy but i have a restriction:
the data type cannot be a string or a char, thats why i am using an int, but when i introduce a real big number like 100100010000100 the code just doesn´t work properly, how could i solve this, any ideas???if someone could help me out with this i would appreciate it a lot
#include <iostream>
using namespace std;
int searchDigit(long int num,int digit);
int main()
{
long int num;
int digit,x;
cout << "Give me the number: " << endl;
cin >> num;
cout << "Digit " << endl;
cin >> digito;
x = searchDigit(num,digit);
cout << "\nThe digit " << digit << " appears " << x << " times" << endl;
return 0;
}
int searchDigit(long int num,int digit)
{
int r,c,p = 0;
for(c = num;c != 0;c = c/10)
{
r = c % 10;
if(r == digit)
p++;
}
return p;
}
Notice that in searchDigit you have c = num in the for-loop. If long int is larger than int - which is true on many platforms - you will lose the high bits of num.
If you enabled more compiler warnings, this would probably be picked up. It's hard to be more specific, since you haven't provided information about the platform, compiler, or the flags used.