Breedly
Breedly

Reputation: 14286

Command Line Input Working Incorrectly

Okay so I made this program to help me out with my homework and because I wanted to improve my C expertise. Everything compiles fine when I do "gcc file.c -lm", but when I run it with a number at the command line as an argument, my program only returns 70.0000.

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


double temp(double hour){
    double t = (3.14/12)*hour;
    double c = cos((double)t);
    double temp = 13 * c + 57;
    return temp; 
}

int main ( int argc, char *argv[]){
    double temperature = temp((double)atol(argv[0]));

    printf("%f\n", temperature);
}

Upvotes: 6

Views: 93

Answers (2)

Carl Norum
Carl Norum

Reputation: 225112

argv[0] is probably your program name. You want argv[1], I expect. Check out this tutorial for a quick and easy explanation.

Besides that, is there a reason you're using atol(3) and casting to double rather than just using atof(3) which returns a double directly?

Upvotes: 7

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

Remember, that argv is the arguments used to launch the program, which looks something like this:

/path/to/my/exec value

So, when you access the first element of that array, argv[0], you are accessing the following:

/path/to/my/exec

What you really need is the second element of the array, argv[1], which should contain this:

value

Upvotes: 3

Related Questions