-2

I am trying to convert argv[1] to a floating point value but I end up with an compilation error. Here is my code.

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

int main(int argc, char *argv[])
{

        double circleArea = 3.14159 * atof(argv[1]) * atof(argv[1]); //this works

        double circleArea = 3.14159 * (double) argv[1] * (double) argv[1]; //this does not

        return 0;

}`

Why does the first statement compile and the second one does not? Should not the (double) argv[1] be just as valid as atof(argv[1])? I want to be able to do this in plain C not C++.

Update: These are the errors I get:

circleArea.c: In function ‘main’:
circleArea.c:9:2: error: pointer value used where a floating point value was expected
  double area = 3.14159 * (double) argv[1] * (double) argv[1]; //this does not
  ^~~~~~
circleArea.c:9:2: error: pointer value used where a floating point value was expected
gotoat
  • 31
  • 6

1 Answers1

0

The problem you are seeing is related to cast/conversion. In the second line - where you are getting error - you need to convert the string to double, but you are not - you are just casting the value, i.e. "telling the compiler that what you have there is a double", which is not.

Casting works in C for similar types - int to float, short to double, float to long, char to int. Of course, you might lose precision in some of the conversions there. However, you can't, for instance, convert a int [] to int (actually, you might, but you certainly have unexpected results) because one is an array and the other is a single variable.

To make it work, you should use atod function. Check this post for details.

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53