所以我想以命令行的形式运行程序: (./program -f)或(./program -c)取决于我是否要将数字从华氏温度转换为摄氏温度(-f)或摄氏温度转换为华氏温度(-c)。我遇到的问题是我收到错误/警告。我相信我的方法是正确的,但我仍在发展我的技能。
#include <stdio.h>
#include <string.h>
float c2f(float c);
float f2c(float f);
float c2f(float c)
{
return (9 * c/5 +32);
}
float f2c(float f)
{
return ((f - 32) * 5/9);
}
int main(int argc, char const *argv[])
{
char c[3];
char f[3];
strcpy(c, "-c");
strcpy(f, "-f");
char **p = &argv[1];
if(strcmp(p, c) == 0)
{
float returnc = c2f(atof(argv[2]));
printf("%f\n", returnc);
}
else if(strcmp(p, f) == 0)
{
float returnf = f2c(atof(argv[2]));
printf("%f\n", returnf);
}
else
printf("Wrong\n");
return 0;
}
这是我得到的警告:
warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
char **p = &argv[1];
warning: passing argument 1 of ‘strcmp’ from incompatible pointer type [-Wincompatible-pointer-types]
if(strcmp(p, c) == 0)
note: expected ‘const char *’ but argument is of type ‘char **’
extern int strcmp (const char *__s1, const char *__s2)
warning: implicit declaration of function ‘atof’ [-Wimplicit-function-declaration]
float returnc = c2f(atof(argv[2]));
warning: passing argument 1 of ‘strcmp’ from incompatible pointer type [-Wincompatible-pointer-types]
else if(strcmp(p, f) == 0)
note: expected ‘const char *’ but argument is of type ‘char **’
extern int strcmp (const char *__s1, const char *__s2)
我运行了我的代码,它只是默认为“Wrong”,这意味着它无法识别-f / -c。
答案 0 :(得分:1)
您有分段错误和其他语法错误。您还没有包含库。我调试了你的代码并且它可以工作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
float c2f(float c);
float f2c(float f);
int main(int argc, char** argv)
{
char c[3];
char f[3];
strcpy(c, "-c");
strcpy(f, "-f");
char* p = argv[1];
char* s=argv[2];
float temp=atof(s);
printf("%s value of p given and value of temperature %f\n",p,temp);
if (argc<3)
{
printf("Please specify two parameters \n");
}
else
{
if(strcmp(p, c) == 0)
{
float returnc = c2f(temp);
printf("%f\n", returnc);
}
else if(strcmp(p, f) == 0)
{
float returnf = f2c(temp);
printf("%f\n", returnf);
}
else
{
printf("Specify either -c or -f as parameters\n");
}
}
return 0;
}
float c2f(float c)
{
return (9 * c)/5 +32;
}
float f2c(float f)
{
return (f - 32) * 5/9;
}
将来,请提供您收到的错误或警告类型,以便人们更方便地帮助您。