Thread: variable value not assignment to function argument

  1. #1
    Registered User
    Join Date
    Feb 2010

    variable value not assignment to function argument

    [I'm new to C programming and I have this assignment that requires me to design a program that asks a user to guess a value and then the program will calculate the derived value from the input using a mathematic equation given in the assignment. The problem I'm having is that after the user enters the value, it is not assigned to the variable and as a result I keep getting weird values when I printf the input value. For e.g
    int main {
    double x;
    printf ("Please guess a value: ");
    calculate (x);
    return 0;
    calculate (double x) {
    char buf[20];
    char *p;
    if (fgets (buf, sizeof(buf), stdin) != NULL) {
    x = strtod (buf, &p);
    if (buf[0] != '\n' && (*p == '\n' || *p == '\0')) {
    if (x > 0) {
    printf ("Value = %d", x);
    The above is similar to part of my code. It appears that the value entered is not assigned to the variable x after the input is deemed valid using fgets. I'm not sure why is this so so can anyone tell me what's wrong with my code?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    %d format in printf is for int

    double var should be printed with %f
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

  3. #3
    Join Date
    Oct 2007
    Inside my computer
    First, you need to indent the code.
    Secondly, x's value will not reflect in main because a local copy of x is made inside the function. You need a pointer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM