C programming - floating point exception - c

matthewmpp#annrogers:~/Programming/C.progs/Personal$ cat prime4.c
/*
* File: main.c
* Author: matthewmpp
*
* Created on November 7, 2010, 2:16 PM
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
/*
prime numbers.
version4
should tell whether a number is prime or not prime.
by using other prime numbers.
*/
int input_func ()
{
char line[100];
int n_input;
while (1) {
printf("Please enter a whole number.\n");
fgets(line, sizeof (line), stdin);
sscanf(line, "%d", &n_input);
if (n_input >= 0)
break;
return (n_input);
}
}
int ifstatements_func (n_ifstate)
int n_ifstate;
{
if (n_ifstate == 0) {
printf("The number, %d, is not prime and has no factors.\n", n_ifstate);
exit(1);
}
if (n_ifstate == 1) {
printf("The number, %d, is not prime.\n", n_ifstate);
printf("The factors of %d, is %d.\n", n_ifstate, n_ifstate);
exit(1);
}
if (n_ifstate == 2) {
printf("The number, %d, is a prime.\n", n_ifstate);
printf("The factors of %d, are 1 and %d.\n", n_ifstate, n_ifstate);
exit(1);
}
if (n_ifstate == 3) {
printf("The number, %d, is a prime.\n", n_ifstate);
printf("The factors of %d, are 1 and %d.\n", n_ifstate, n_ifstate);
exit(1);
}
return (n_ifstate);
}
int square_root_func (n_prmfnc)
int n_prmfnc;
{
int i; //counter
float sq_root_f;
int sq_root_i;
int primes[100];
int length_primes;
primes[0] = 2; /*first prime is 2.*/
primes[1] = 3; /*second prime is 3.*/
length_primes = sizeof (primes);
//printf ("before.sq_root.value of n_prmfnc=%d\n", n_prmfnc);
sq_root_f = sqrt(n_prmfnc);
sq_root_i = sq_root_f;
//printf ("prmfnc.after.sq_root\n");
//printf ("value of sq_root=%.3f\n", sq_root_f);
//printf ("value of sq_root=%d\n", sq_root_i);
return (sq_root_i);
}
int prime_func (sq_root_pf, n_pf)
int sq_root_pf, n_pf;
{
int prime_counter;
int prime_temp;
int prime_flag=0;
int primes_pf[100];
int i; //counter
primes_pf[0]=2;
primes_pf[1]=3;
primes_pf[2]=5;
printf ("before.for.in.pf");
for (i = 0; i <= 100; ++i) {
printf ("after.for.in.pf");
if (primes_pf[i] <= sq_root_pf) {
printf ("before.modulus.in.pf");
prime_temp = n_pf % primes_pf[i];
printf ("after.modulus.in.pf");
if (prime_temp == 0) {
++prime_counter;
if (prime_counter == 0)
prime_flag = 1; /*yes, number is prime.*/
}
}
}
return (prime_flag);
}
int main() {
int n_main1; //number from input
int n_main2; //number after if statements
int sq_root_main; //square root of number from function
int prime_flag_main; //value of 1 if it is a prime
n_main1 = input_func ();
printf("main.after.input.function=%d.\n", n_main1);
n_main2 = ifstatements_func (n_main1);
printf ("main.after.ifstatments.function=%d\n", n_main2);
sq_root_main = square_root_func (n_main2);
printf ("main.after.square_root_func_func=%d\n", sq_root_main);
prime_flag_main = prime_func (sq_root_main, n_main2);
printf ("main.after.prime_func=%d\n", prime_flag_main);
return (EXIT_SUCCESS);
}
OUTPUT:
matthewmpp#annrogers:~/Programming/C.progs/Personal$ cc -c prime4.c
matthewmpp#annrogers:~/Programming/C.progs/Personal$ cc -o prime4 prime4.c -lm
matthewmpp#annrogers:~/Programming/C.progs/Personal$ ./prime4
Please enter a whole number.
44
main.after.input.function=44.
main.after.ifstatments.function=44
main.after.square_root_func_func=6
Floating point exception
matthewmpp#annrogers:~/Programming/C.progs/Personal$
STATEMENT: the error is in the prime_func. I believe the cause is the modulus (% sign).
QUESTION: why am I getting the Floating Point Exception and how do I fix it?

What happens is a division by zero. You only initialise the first three entries of primes_pf, but iterate over all of them (actually, your loop runs even one past the last entry; use i < 100 instead of i <= 100 to fix this). For all but the first three entries, you divide by some unitialised quantity, and one of the entries apparently happens to be zero. Don't use unitialised values.

"Floating point exception" is a misnomer. It only happens on integer division by zero and a few other division-related operations.

Not sure I believe the answer above!
X = 5.0;
Y = 0.0;
Z = X/Y;
This will give a floating point exception....
The problem would appear to be that prime_pf is only initialised for 3 elements. So the modulo is attempting to divide by zero.
BTW, if you add \n to your printf statement, and add the extra statement
fflush(stdout);
you are more likely to see the debug output before the program errors.

The problem exists in your primes_pf variable. You seemed to have initialized the first three elements of this integer array, but when iterator i goes beyond 2, primes_pf[i] is reading from uninitialized memory and getting compared to sq_root_pf; that can't be right.
I haven't taken the time to fully understand your algorithm but my best guess is that you forgot to assign a new value to primes_pf somewhere in your for loop.

sqrt(x) needs x to be of type double, you have used int.
Cast to double (double)n_prmfnc
I am VERY sure about this !

Related

Average of Even Numbers and Product of all Odd Numbers

#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.

Write a program that multiplies user entered number till product of these numbers reach 1000

I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

Decimal To Binary conversion using Array and Stack

This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);

Problem with scanf, C. Floating point exception

i'm learning C.
i'm using ubuntu and have Code::Blocks as IDE
i have this code:
#include <stdio.h>
int rev (int num);
int main (){
int numb = 0;
printf("%d\n\n", numb);
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
printf("there?");
printf("%d\n", numb);
while (numb != 9999){
printf("The reversed number is %d\n", rev(numb));
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
} /* end of while */
}
int rev (int num){
printf("here?");
int total = 0;
long max = 10;
long max_const = 10;
printf("here");
for (max; max < num; max *= 10);
printf("%ld", max);
max_const = max;
for (int i = 0; i <= max_const; i *= 10, max /= 10){
total += num / max * i;
} /* end for */
return total;
}
I'm doing it in this way cause my book isn't clear...however, the problem is that it raise a Floating Point exception, in scanf...i'm typing normal numbers... the strange thing is that if i type everything but 9999, the program crash. if i type 9999, it prints 'there?' (so scanf it's ok) and stop later, obviously. why?
Thank you.
The two existing (be sure to return the result in rev, and put \n on the ends of printfs to be sure they make it through the buffer) answers are good points, but not the thing that's actually triggering your floating point exception. Try running it in a debugger, and you'll see that your algorithm is bad: eventually max becomes zero and you divide by it. I'll leave fixing that as an exercise for the reader; the problem isn't anything to do with scanf.
Your rev function needs to return the reversed number.

Resources