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.
Related
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;
}
}
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/
I use rand function to generate two random numbers, numerator and denominator, that are used in division, sometimes the result is float and sometimes is integer. How can I generate only an integer result ? here is my code :
srand(time(NULL));
integer1 = ((rand() % ( 81 - 5 ) + 5 )*2);
integer2 = ((rand()%3 + 1)*2);
answer = integer1/integer2;
do {
cout << "How much is " << integer1 << " divided by " << integer2 << " ? : " << endl;
cin >> answer;
if (answer == integer1/integer2) {
cout << "Very Good !"<< endl;
}
else {
cout << "Your answer is false, please try again !"<<endl;
}
} while ((integer1/integer2!=answer));
If both operands of / are integral types, the result will be integral. If either operand is a floating point type the result will be a floating point type. If you want it to be a truncated integer you'll need to cast to the type you desire.
So here's the code:
if(rand_s(&number) != 0) cout << "Random number generator failed!" << endl;
Question is - does it mean that the program outputs a failure message every time the random number generated with this rand_s(&number) expression is greater than zero? And if so, why would i want such a thing?
// complete code
unsigned int number = 0;
cout << "Random values are:" << endl;
double max = 1000000.0;
for(int i = 0 ; i<100 ; i++)
{
if(rand_s(&number) != 0)
cout << "Random number generator failed!" << endl;
number = static_cast<unsigned int>(static_cast<double>(number)/UINT_MAX*max)+1;
// output
cout << setw(12) << number;
if((i+1) % 5 == 0) cout << endl;
}
No rand_s returns an errno_t so 0 means there was no error. Anything else is indicating that there was an error when running the function.
More information can be found here
No. here is the link.
rand_s return value: Zero if successful, otherwise, an error code.
Your random value will be: number
The return value of function is 0 if the function execution completes successfully. The result is stored in number. Note that you are passing by address.
So I have this program:
#include <iostream>
using namespace std;
bool prime(int input)
{
// cout << "pinput: " << input << endl;
int i = ((input/2) + 1);
// cout << "pi: " << i << endl;
int c;
for (i>0; i--;){
//cout << "pi: " << i << endl;
if (input == 3 || input == 2){
// cout << "true" << endl;
return true;
}
if (input == 1){
// cout << "pi = 1" << endl;
return false;
}
c= input%i;
if (c==0 || i == 1 ){
// cout << "false" << endl;
return false;
}
else if (c!=0 && i<4){
// cout << "true" << endl;
return true;
}
}
return 0;
}
int factor(int input){
// cout << "finput: " << input << endl;
int i = (input/2) + 1;
int c;
int e;
bool d = false;
for (i>0; i--;){
// cout << "fi: " << i << endl;
c = input%i;
if (c==0){
d = prime(i);
if (d==true){
// cout << "found" << endl;
return i;}
}
if (i==1){
// cout << "fi = 1";
return 0;
}
//cout << "not prime" << endl;
}
return 0;
}
int main(){
int woot;
cout << "Please insert quater: " <<endl;
cin >> woot;
int answer;
answer = factor(woot);
if (answer == 0)
cout << "no prime factors" << endl;
else
cout << "answer is: " <<answer << endl;
return 0;
}
It seems to work until I put a really big number in like more specifically the number 600851475143, in which case I always get different answers when I run that number now I'm pretty sure it's just exceeding the size of it's variable type. Now then I was looking and I can't find the right variable type for a number that big, I int and long seem to be for numbers that are for numbers up to 4294967295 if unsigned however that is only 10 digits long, mine is 12. What type of variable should I use? Or will that even fix the problem? The program is to find the largest prime factor of a number (Euler problem 3). Any tips links or advice would be appreciated. And of course an answer extra appreciated! :D
Interesting typo alert!
This is unlikely to be doing what you think it is doing...
for (i>0; i--;){
While it is perfectly legal syntax, and will loop the correct number of times, the value of i inside the loop is (probably) going to be one less than you intended...
% cat 4237157.c++
#include <iostream>
int main()
{
{
std::cout << "Your loop: " << std::endl;
int i = 10;
for (i>0; i--;)
{
std::cout << i << std::endl;
}
}
{
std::cout << "More conventionally: " << std::endl;
for (int i = 10; i > 0; i--)
{
std::cout << i << std::endl;
}
}
return EXIT_SUCCESS;
}
% g++ -o 4237157{,.c++}
% ./4237157
Your loop:
9
8
7
6
5
4
3
2
1
0
More conventionally:
10
9
8
7
6
5
4
3
2
1
The syntax for a for-loop in C-like languages is:
for (variable initialization; conditional; variable increment)
You are evaluating "i>0" instead of doing any initalization. This may as well be blank. Then you are evaluating whether i-- is zero. Since i is post-decremented, your loop starts with i being one less than it was initialized with before the loop, executes until (and including) being equal to zero and then terminates.
A lot of the problems on Project Euler call for arbitrary-precision arithmetic, which isn't covered by the C++ standard library.
Have a look at the C++ Big Integer Library.
If you want arbitarily big numbers, you need an arbitary precision arithmetic library
unsigned long 4294967295
unsigned long long 18446744073709551615
unsigned long long is not standard C++, but most compilers support it as an extension. The maximum should be at least 2^64 - 1, which is more than enough.
If you later want even larger numbers, you can use a arbitrary precision library such as GMP. They have a C++ interface.