-2

数日前に C でプログラミングを始めたばかりで、いくつか質問があります。

次のプログラムは、摂氏を華氏に、またはその逆に変換します。セグメンテーション違反エラーが発生します。

#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);
}

また、出力を次のようにしたい:

**> 温度コンバータ -> f 10.0

10.00°C = 50.00°F**

これで 10C が F に変換されます。

F から C の場合、出力は次のようになります。

温度コンバーター ->c 50.0

50.00°F = 10C**

4

3 に答える 3

0

ちょっとしたコツ:

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

技術的には正しいですが、変数名も関数宣言に含めることを忘れないでください。読みやすくなります。

例として

float c2f(float c);
于 2013-10-16T23:21:20.763 に答える