我正在制作一个简单的货币转换器,将瑞典克朗转换为欧洲欧元或美国美元。当它应该打印出转换时,程序只是终止。Visual Studio Code说代码没有问题,所以我不明白原因。
代码:
#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;
}
if (currency == "USD")
添加#include <string.h>
,然后添加
if (strcmp (currency, "USD") == 0)
还要注意,不测试scanf的返回值总是一个错误。您认为您可以假设输入是格式良好的,但特别是用户输入通常不是。
接下来,要读取字符串,您不能使用%c
,但必须使用%s
。不要盲目地这样做,关于如何限制输入的大小以避免溢出您的货币[]数组,有很多问题。搜索它们。如果它提到fgets((,请仔细查看。
您还应该养成在字符串的结尾处写入新行n
的习惯,因为这是刷新行缓冲输出的时候("出现"(。Windows在程序结束时总是附加一行换行,这导致了printf ("nwhatever")
这种常见的可憎之处。
此代码中有两个主要问题:
- 使用scanf时,您正在等待
char *
输入,但%c正在接受char
。将其更改为%s - C不允许使用"=="运算符进行字符串比较。您应该使用strcmp((