0

I cannot get the exponential to work with user input. Every time user is prompted to add input, after the input is entered the program immediately closes.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
   double input = 0;
   double exp_val;
   printf("Plese enter the exponent to check for convergence:");
   scanf("%f", input,"\n");
   printf("%f", input);/*Checking to verify the input is entered*/
   exp_val = exp(input);
   printf("%f", exp_val);
   getchar();
}
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
user3259144
  • 71
  • 1
  • 9

2 Answers2

1

scanf expects a pointer to the double, not the double itself:

scanf("%lf", &input);

This is because passing input directly passes by value. But scanf doesn't want to know the current value of input, it wants to know the memory location where it should write the data that it reads.

happydave
  • 7,127
  • 1
  • 26
  • 25
  • I added the pointer, and it still crashed. Is there something I need to do to the double when it is initialized? – user3259144 Feb 28 '14 at 04:44
  • Try adding a second call to getchar. Or read this: http://stackoverflow.com/questions/12653884/getchar-does-not-stop-when-using-scanf – happydave Feb 28 '14 at 04:58
1

Besides @happydave's answer to use &input, you also need the %lf format specifier to read a double:

scanf("%lf", &input);

Check out Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?


After this, you should get the correct answer, see it live: http://ideone.com/246clu.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174