سؤال

I just started programming in C a few days ago and have a few questions:

The following program converts Celsius into Fahrenheit and vice versa. I am getting a Segmentation fault error.

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

float c2f(float);
float f2c(float);

float Fahrenheit,Celsius;

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

/** 
 * Check for the expected number of arguments (3)
 * (0) program name
 * (1) flag
 * (2) temperature
 */
if (argc!=3)
    printf("Incorrect number of arguments");

if (!strcmp(argv[1], "->f"))
{
   // convert the string into a floating number
   char *check;
   float Celsius = strtod(argv[2], &check);

// process from celsius to fahrenheit
   Fahrenheit = c2f(Celsius);
   printf("%5.2f°C = %5.2f°F",Celsius, Fahrenheit);
}   
else if (!strcmp(argv[1], "->c"))
{
   // convert the string into a floating number
   char *check;
   float Fahrenheit = strtod(argv[2], &check);

   // process from fahrenheit to celsius
   Celsius = f2c(Fahrenheit);
   printf("%5.2f°F = %5.2f°C", Fahrenheit, Celsius);


}   
else
   printf("Invalid flag\n");
} // main


float c2f(float c)
{
  return 32 + (c * (180.0 / 100.0)); 
} 

float f2c(float f)
{
  return (100.0 / 180.0) * (f - 32);
}

Also, I want my output to be like this:

**> TemperatureConverter ->f 10.0

10.00°C = 50.00°F**

This should convert 10C into F.

For F to C, the output should be:

TemperatureConverter ->c 50.0

50.00°F = 10C**

هل كانت مفيدة؟

المحلول

the error is if (!strcmp(argv[1], "->f")

it's missing a final parenthesis, should be

if (!strcmp(argv[1], "->f"))

and you made the same mistake twice. 1 paren for strcmp(), 1 for if()

you should include string.h. Also, you should put you functions f2c and c2f before main.

also you wrote

prinf

try with a t before the f

printf

finally you need

exit(0);

after the first if. eg

if (argc!=3)
{
    printf("Incorrect number of arguments");
    exit(0);
}

otherwise the rest of the program runs and you get seg fault. Welcome to programming.

نصائح أخرى

Slight nitpicking:

float c2f(float);
float f2c(float);

While it's technically correct, remember to include the variable name as well in your function declarations. It makes it easier to read.

As an example

float c2f(float c);

I used this code :

/* Declare Initial library for functions */
    #include<stdio.h>
    #include<conio.h>

    /* Main function*/
    void main()
    {
     /* data type(float),variable(c,f)*/   
     float c, f;

    /* printf function from stdio.h library , for printing level*/
     printf("Enter temp. in Celsius: ");

    /* scanf for inserting data in variable*/
     scanf("%f",&c);

      /* Fahrenheit rules*/
     f = c * 9/5 + 32;

     /* Result will display in this line */
     printf("Temp. in Fahrenheit: %f",f);

    /* getch function from conio.h library, used to write a character to screen*/
     getch();
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top