This program compiles fine, but it returns a message "Floating Point Exception" when I run it. I've looked at other threads and the problem appears to be dividing by 0, but I have looked over the program and there's no division by zero in my entire program. I even used the absolute value function in case.
By the way, the program is meant to reduce fractions.
Example input: 6 12, representing the fraction 6/12
Expected output: 1/2
#include <stdio.h>
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
/*declaring functions*/
int find_gcd(int num1, int num2);
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator);
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(higher, lower, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
num1=numerator;
num2=denominator;
gcd =find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
int find_gcd(int m, int n)
{
while (n != 0) {
int remainder = m % n;
m = n;
n = remainder;
}
return m;
}
Your main problem is that you are not passing your input values num1 and num2 into your reduce() function. Instead you are passing in the global variables higher and lower. You didn't assign any values to them, but global variables are always initialized to 0 by default. Therfore, you run into the exception, because in reduce() you divide 0 by 0. You can verify that with a debugger.
If I change your main() as follows, then your code is at least working for your test case with 6 and 12 as input:
int main(void)
{
do
{
printf("enter 2 numbers: ");
scanf("%d %d", &num1, &num2);
reduce(num1, num2, &higher_2, &lower_2);
printf("enter 0 to end program and any number continue: \n");
scanf("%d", &x);
} while(x != 0);
return 0;
}
Output:
enter 2 numbers: 6
12
The GCD is 1/2
enter 0 to end program and any number continue:
As indicated in the comments you should also get rid of global and spurious variables. Therefore, you should first delete the following lines in your code:
/*declaring variables*/
int num1, num2, num1b, num2b, gcd, x;
int higher, lower, higher_2, lower_2;
Then let your main() function start the following way:
int main(void)
{
int num1, num2, higher_2, lower_2, x;
...
}
And your reduce() function should read like this:
void reduce(int numerator, int denominator, int *reduced_numerator, int *reduced_denominator)
{
int gcd = find_gcd(numerator, denominator);
*reduced_numerator = (numerator/abs(gcd));
*reduced_denominator = (denominator/abs(gcd));
printf("The GCD is %d/%d\n", *reduced_numerator, *reduced_denominator);
}
So far, you don't use your variables higher_2 and lower_2 in the main() function, but I guess you plan to do so. If not, you can also get rid of them together with parameters 3 and 4 of your reduce() function.
There is another issue with the code you provided (thanks to #user3629249 for pointing it out): You are missing an include for the abs() function. So you need to add the line #include <stdlib.h> at the beginning of your code (include <math.h> will also so the trick, as well as include <Windows.h> on Windows).
Related
I made a program to convert decimal to binary but it is not working for big outputs. I think I am not able to use long long int in my function properly.
Here is my code:
#include<iostream>
using namespace std;
int decimal_to_binary(int n)
{
int x=1;
long long int ans=0;
while (x<=n){
x*=2;
}
x/=2;
while(x>0)
{
int lastdigit=n/x;
n-=lastdigit*x;
x/=2;
ans=ans*10+lastdigit;
}
return ans;
}
int main()
{
int input;
long long int a;
cout<<"input = ";
cin>>input;
a=decimal_to_binary(input);
cout<<a;
}
For example,
if I input 30 it gives me expected output i.e. 11111.
The program gives correct output up to 1023 input,
but after that it gives me unexpected value. For example,
if I input 1200 then output is 1420175408.
You're storing a decimal number which is the binary representation of n reinterpreted as decimal.
If n>2047, ans will overflow a std::int32_t; if n>524287, ans will overflow a std::int64_t (the biggest signed 64-bit number is 9223372036854775807; unsigned would allow one more bit in ans).
The proper thing to return is a string. Try this:
std::string decimal_to_binary(int n)
{
int x=1;
std::string ans;
while (x<=n){
x*=2;
}
x/=2;
while(x>0)
{
int lastdigit=n/x;
n-=lastdigit*x;
x/=2;
ans=ans+(char)('0'+lastdigit);
}
return ans;
}
Three positive nos. A,B,C.Find no. of pos integers less than D divisible by either a,b,c. Well the test cases ran fine with one but for submitting it needed more optimised code. How can it be more optimised?
solve(int A, int B, int C, int D) {
int X = 0;
for (int i = 1; i < D; i++)
{
if (i%A==0 || i%B==0 || i%C==0)
{
X++;
}
}
return X;
}
The idea is simple take any number ,let it be 11,to find how many numbers are divisible by 3 we just need to find 11/3=3 i.e 3,6,9
Hence we add all the elements that are divisible by A or B or C.
But we also find that numbers like 24 are divisible by both 3 and 4 hence they will be counted twice if A=3 and B=4 so we subtract the amount that are divisible by both,i.e the ones divisible by lcm(3,4)=12. Similarly for the numbers divisible by all three should be added as it was subtracted multiple times.
Code is...
#include<iostream>
using namespace std;
int lcm(int a, int b);
int gcd(int a, int b);
int solve(int A,int B,int C,int D)
{
int divisibleA=D/A; //positive Numbers divisible by A
int divisibleB=D/B;
int divisibleC=D/C;
int divisible_A_B= D/(lcm(A,B)); //positive numbers that were divisible by A and B both These were counted twice
int divisible_A_C= D/(lcm(A,C));
int divisible_B_C= D/(lcm(B,C));
int divisible_A_B_C=D/lcm(lcm(A,B),C); //positive numbers divisible by all three
return divisibleA+divisibleB+divisibleC-divisible_A_B-divisible_A_C-divisible_B_C+ divisible_A_B_C;
}
int main()
{
int a,b,c,d;
cin>>a>>b>>c>>d;
cout<<solve(a,b,c,d)<<endl;
}
int gcd(int a, int b)
{
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Function to return LCM of two numbers
int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
EDIT: The following should work:
int solve(const std::vector &array_of_numbers, int size, int divider){
int count = 0;
for (int i=0; i<size; i++){
if (array_of_numbers.at(i)%divider == 0){
count++;
}
}
return count;
}
so Im trying to calculate a number raised to a power from user input, using scanf, but i keep on getting a segmentation fault.Does any one know why?This is my code:
int power( int base, int exponent){
int total=1;
int temp = power(base, exponent/2);
if (exponent == 0)
return total; // base case;
if (exponent % 2 == 0)// if even
total= temp * temp;
return total;
if(exponent %2 !=0)// if odd
total =(base * temp * temp);
return total;
}
void get_info(){
int base, exponent;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter an exponent: ");
scanf("%d", &exponent);
//call the power function
printf("%d",power(base,exponent));
}
int main(){
//call get_info
get_info();
return 0;
}
Any help would be much appreciated.Thank you.
There's nothing to block the recursion in power:
int power( int base, int exponent){
int total=1;
int temp = power(base, exponent/2); // round and round we go
The solution is to put
if (exponent == 0)
return total; // base case;
at the top of the function. C++ runtime libraries often issue a misleading termination message on a stack overflow such as this.
I'd also be tempted to use an else rather than testing the odd case explicitly. And fix the glaring issue with some missing { and }.
I don't understand why the following code always answers with 0.
#include <iostream>
using namespace std;
int main() {
int n,a,b;
cin>>n;
b=n%10;
while(n!=0) {
a=n%10;
n=n/10;
}
a=b;
b=a;
cout<<n<<endl;
return 0;
}
To swap two numbers, you need a temporary register
tmp=a;
a=b;
b=tmp;
However, if you are trying to swap digits in n, you need to change n. Which you have destroyed in your loop. Keep a copy of it beforehand?
Or simply note that floor(log(n)/log(10)) gives you the power of 10 for the first digit.
n=23456;
int firstdec = pow(10,floor(log(n)/log(10))); // eg 10000
int firstdig = n/firstdec; // eg 2
int lastdig = n%10; // eg 6
int removed = ((n-firstdig*firstdec)/10)*10 ; // eg 3450
int final = removed + lastdig*firstdec + firstdig; // eg 63452
This
a=b;
b=a;
looks nice.
Do you mean swap(a, b) or
int t = a;
a = b;
b = t;
?
And you're not actually changing n.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num, swno;
int fd, ld, digits;
// Reads a number from user
cout<<"Enter any number:";
cin>>num;
ld = num % 10; //Gets last digit
digits = (int)log10(num); //Total number of digits - 1
fd = (int)(num / pow(10, digits)); //Gets the first digit
swno = ld;
swno *= (int)pow(10, digits);
swno += num % ((int)pow(10, digits));
swno -= ld;
swno += fd;
cout<<"\nOriginal number = "<<num;
cout<<"\nNumber after swapping first and last digit: "<<swno;
return 0;
}
You code has some problems, like the variable swap. But also, you seem to expect that by changing a and b, n is changed accordingly, which is not going to happen.
First, because a and b are not references to the digits, they are mere copies. Second, you destroyed you n in the loop finding a, so even when you fix you swap the code will still print 0.
My recommendation is to convert the integer to a string, change the first and last, and then convert it back. It will be much simpler and more readable.
In order to do that you should take a look at stringstreams.
#include <iostream>
#include<string.h>
using namespace std;
int main(void){
int a;
char k,l;
cin>>a;
string s=to_string(a);
k=s[0];
l=s[s.length()-1];
s[0]=l;
s[s.length()-1]=k;
cout<<s;
return 0;
}
Here is what is missing in your code. real= entered value, first and last digits = firstd and lastd and i = number of digits of the entered number.
real -= lastd;
real += firstd;
real -= (firstd*i);
real += (lastd*i);
#include <iostream>
using namespace std;
double calc(int a, int b);
int main()
{
int n1, n2;
cout << "Enter a number for a: ";
cin >> n1;
cout << "Enter a number for b: ";
cin >> n2;
cout << calc(n1, n2) << endl;
system("PAUSE");
return 0;
}
double calc(int a, int b)
{
double s;
s = (a) / ((sqrt(a / b)));
return s;
}
This program is meant to check whether the two integers are greater than zero. If it is it will calcualte the formula. Otherwise if one of the integers is zero or less than zero it will not return anything and exit the program.
My question here is that no matter what I input for a and b, i keep getting 1.#INF as the output and I have no idea why. I've checked the formula in a seperate program and it worked fine.
Any ideas?
Here, you are operating with int numbers:
s = (a) / ((sqrt(a / b)));
If a is less then b, then a/b (both are integers, remember, so the fractional part of the result will simply be lost) will be equal to 0, which leads to division by 0. You need to cast one of the numbers to double:
s = (a) / ((sqrt(static_cast<double>(a) / b)));
sqrt takes and returns a double. When you call it with integer arguments it will be converted in a double, and will thus get the value of infinity.
change your function signature to:
double calc(double a, double b);
and declare n1 and n2 as double.
You say that the function will exit the program when one of the integers are 0 or less, but where?
Try to check them like this:
Additionally, you should have a check whether a is greater than b
double calc(int a, int b)
{
double s;
if(a <= 0) exit(-1);
if(b <= 0) exit(-1);
if(a < b) exit(-1);
s = (a) / ((sqrt(a / b)));
return s;
}
You are having problems with infinity. For it use isinf. Here is some sample usage:
#include <stdio.h> /* printf */
#include <math.h> /* isinf, sqrt */
int main()
{
printf ("isinf(-1.0/0.0) : %d\n",isinf(-1.0/0.0));
printf ("isinf(sqrt(-1.0)): %d\n",isinf(sqrt(-1.0)));
return 0;
}
output:
isinf(-1.0/0.0) : 1 isinf(sqrt(-1.0): 0