我正在制作一个简单的货币转换器,将瑞典克朗转换为欧洲EUR或美国USD。当它应该打印转换时,该程序只是终止。 Visual Studio代码说代码没有问题,所以我不明白这个原因...
代码:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
float SEK;
const float EUR = 0.0920;
const float USD = 0.1000;
const float YEN = 10.7600;
char currency [256];
printf("Enter amount of money you want to convert in SEK: ");
scanf("%f", &SEK);
printf("Enter the desired currency to convert to: ");
scanf(" %c", ¤cy);
if (currency == "EUR") {
printf("\nFor %.4f SEK, you get: %.4f EUR", SEK, SEK*EUR);
}
else if (currency == "USD") {
printf("\nFor %.4f SEK, you get: %.4f USD", SEK, SEK*USD);
}
getchar();
getchar(); //used to give me a proper end on output of my program
return 0;
}
C中的字符串比较使用strcmp()函数。您无法使用
if (currency == "USD")
添加#include <string.h>
,然后
if (strcmp (currency, "USD") == 0)
还请注意,不测试scanf的返回值是总是错误。您认为您可以假设输入格式正确,但是尤其是用户输入通常不是这样。
接下来,要读取字符串,您不能使用%c
,但必须使用%s
。不要盲目地做,关于如何限制输入量的大小有很多问题,以免使您的currency []数组溢出。搜索它们。如果它提到fgets(),请仔细查看。
此代码中有2个主要问题:
char *
输入,但是%c正在接受char
。将其更改为%s。