Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

A problem with C

  1. Dec 27, 2007 #1

    I'm kinda learning C at home by myself and was just to compile another small program when I encountered problem with compiling.

    Here's the code:
    Code (Text):
    #include <stdio.h>
    #include <math.h>

    int main(int argc, char **argv)
        float p, S;

        if (argc != 3)
            fprintf(stderr, "Usage: %s <side_a> <side_b> <side_c> \n", argv[0]);

        p = (argv[1] + argv[2] + argv[3]) / 2;                                //13th line
        S = sqrt(p * (p - argv[1]) * (p - argv[2]) * (p - argv[3]));   //14th line

        printf("Area of this triangle is: %f \n", S);

        return 0;
    and here are the lines from compiler:
    Code (Text):
    kbau@kbox:~/prj/c/test/exercises$ gcc uzd1.c -o uzd1 -Wall
    uzd1.c: In function ‘main’:
    uzd1.c:13: error: invalid operands to binary +
    uzd1.c:14: error: invalid operands to binary -
    uzd1.c:14: error: invalid operands to binary -
    uzd1.c:14: error: invalid operands to binary -
    I'm getting frustrated why isn't this working. I don't understand why is there a problem.

    I don't really have any work to show you except the code, I'm just curious why isn't it working. Help would be appreciated.
    Last edited: Dec 27, 2007
  2. jcsd
  3. Dec 27, 2007 #2
    argv[n] is not a number. It is a char *-- a "string", a series of typed ASCII characters. In order to treat a string like a number, you must first convert it from a "string" to a number. See the man pages for atoi() and atof().
  4. Dec 28, 2007 #3
    Yeah, I figured that out when I woke up during the night but thanks anyway. atof() is the one I need 'cause I have a float there.
  5. Dec 28, 2007 #4

    jim mcnamara

    User Avatar

    Staff: Mentor

    Actually atof returns a double, not a float. Most compilers will "promote" the double to a float for you.

    The reason I mention this - there are a lot of standard C functions that look like they might return a float - modf, atof, for example - when they return a double instead. You need to be careful about assuming what some C function returns just by the name of the function.
  6. Dec 29, 2007 #5
    Ok, thanks, I'll keep that in mind.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook