2015-05-27 5 views
0

Я пытаюсь получить программу, чтобы позволить пользователю ввести валюту, в которую они хотят изменить общую стоимость. когда пользователь вводит неверный ввод, а затем предлагается ввести снова правильную валюту, когда они вводят правильную валюту, цикл while не прерывается. Он снова просит пользователя ввести правильную валюту.Пока цикл не работает для программирования c

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", &currency); 
    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", &currency); 
    } 

    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; 
} 
+1

Последний раз, когда я проверил 'while', было нормально – qrdl

ответ

0

зсапЕ также добавляет \n в конце. Вам нужно либо отрубить это, либо добавить его в строки, которые вы сравниваете. В качестве альтернативы, если вы не заботитесь о том, чтобы кто-то вводил что-то вроде «европейских денег» вместо «евро», вы можете использовать strncmp() вместо strcmp().

Обратите внимание, что ваш код уязвим для переполнения буфера, если кто-то вводит более 98 символов (после добавления \n и \0 вы будете в байте 101). Чтобы убедиться, что это не вызывает проблемы, вместо этого вы должны использовать «scanf («% 99s »)», который отрубает строку после 99-го символа (или, альтернативно, использует другую функцию ввода).

0

Вы используете операторы OR в своем заявлении while, когда вы должны использовать AND. Независимо от того, какая действительная выбранная валюта выйдет из строя 2 из условий, вы застряли в цикле.

+0

Большое вам спасибо! Он работает сейчас, и я понимаю, почему он не смог сломать цикл. –

+0

Никаких проблем, не видел, что логическая ошибка столько раз за эти годы, тоже сработала с ней :-) – OTTA

2

В этой строке while ((strcmp(currency, str1) != 0) || (strcmp(currency, str2) != 0) || (strcmp(currency, str3) != 0))

вы сообщаете свой код в цикле до currency равно str1иstr2иstr3, которые никогда не произойдет.

Вы должны изменить его while ((strcmp(currency, str1) != 0) && (strcmp(currency, str2) != 0) && (strcmp(currency, str3) != 0))

0

Есть sevreal вопросы.

Это условие является неправильным

while ((strcmp(currency, str1) != 0) || (strcmp(currency, str2) != 0) || strcmp(currency, str3) != 0)) 

Заменено:

while ((strcmp(currency, str1) != 0) && (strcmp(currency, str2) != 0) && strcmp(currency, str3) != 0)) 

я позволю вам выяснить причину как exercice.

Ваше использование scanf является слишком сложным, вы, вероятно, хотите:

float gas_gallons; 
float cost_today_gallons; 
int main() 
{ 
    printf("\nPlease enter the number of gallons of gasoline: "); 
    scanf("%f", &gas_gallons); 

    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", currency); 

    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", &currency); 
    } 

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

Bonus: выбор имен переменных str1 к str3 беден. Почему бы не выбрать имена как strEuro, strYen, strPound?

Смежные вопросы