我正在尝试让程序允许用户输入他们想要将总成本更改为的货币。当用户确实输入错误的输入然后被提示再次输入正确的货币时,当他们输入正确的货币时,while 循环不会中断。它不断要求用户再次输入正确的货币。
Please enter the number of gallons of gasoline: 7
7.0 gallons of gasoline produces..
7.0 gallons of gasoline requires..
7.0 gallons of gasoline costs..
Choose a currency you want to see your total cost in (Euro, Pound, or Yen): eurooo
You need choose one of these currencies (Euro, Pound, or Yen). Please enter one: Euro
You need choose one of these currencies (Euro, Pound, or Yen). Please enter one: Euro
You need choose one of these currencies (Euro, Pound, or Yen). Please enter one:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
float gas_gallons;
float cost_today_gallons;
int main()
{
char input;
printf("\nPlease enter the number of gallons of gasoline: ");
scanf(" %c", &input);
getchar();
while (!isdigit(input))
{
printf("\nYou need to enter a digit. Please enter the number of gallons of gasoline: ");
scanf("%c", &input);
}
if (isdigit(input))
{
gas_gallons = input - '0';
float carbon_dioxide_pounds = gas_gallons * 19.64;
printf("\n%.2f gallons of gasoline produces approximately %f pounds of carbon dioxide.", gas_gallons, carbon_dioxide_pounds );
float barrels_crude_oil = gas_gallons/19.0;
printf("\n%.2f gallons of gasoline requires %f barrels of crude oil.", gas_gallons, barrels_crude_oil);
cost_today_gallons = gas_gallons*2.738;
printf("\n%.2f gallons of gasoline costs a total average of %f US dollars today.", gas_gallons, cost_today_gallons);
}
char currency[100];
printf("\nChoose a currency you want to see your total cost in (Euro, Pound, or Yen): ");
scanf("%s", ¤cy);
getchar();
char *str1 = "Yen";
char *str2 = "Euro";
char *str3 = "Pound";
while ((strcmp(currency, str1) != 0) || (strcmp(currency, str2) != 0) || (strcmp(currency, str3) != 0))
{
printf("\nYou need choose one of these currencies (Euro, Pound or Yen). Please enter one: ");
scanf("%s", ¤cy);
}
if ((strcmp(currency, str1) == 0))
{
float yen_total_cost = cost_today_gallons*123.07;
printf("\n%.2f gallons of gasoline costs a total average of %f Japenese Yens today.", gas_gallons, yen_total_cost);
}
if (strcmp(currency, str2) == 0)
{
float euro_total_cost = cost_today_gallons*0.92;
printf("\n%.2f gallons of gasoline costs a total average of %f Euros today.", gas_gallons, euro_total_cost);
}
if (strcmp(currency, str3) == 0)
{
float pound_total_cost = cost_today_gallons*0.65;
printf("\n%.2f gallons of gasoline costs a total average of %f British Pounds today.", gas_gallons, pound_total_cost);
}
return 0;
}
最佳答案
在这一行
while ((strcmp(currency, str1) != 0) || (strcmp(currency, str2) != 0) || (strcmp(currency, str3) != 0))
你告诉你的代码循环直到 currency
等于 str1
and str2
和 str3
永远不会发生。
您需要将其更改为
while ((strcmp(currency, str1) != 0) && (strcmp(currency, str2) != 0) && (strcmp(currency, str3) != 0))
关于c - 虽然循环不适用于 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30485580/