Как выполнить формулу внутри оператора if - PullRequest
0 голосов
/ 17 ноября 2018

Я хотел, чтобы оператор if выполнял код внутри него, но, похоже, он этого не делает вообще, есть идеи о том, как я мог позволить ему выполнять код внутри?Я использовал переменную float F.

#include <iostream>
using namespace std;

int main(){

    int act, choice;
    float F; 

    cout << "Choose any activity below that you want to check by entering the" << endl;
    cout << "number of your choice." << endl;
    cout << "If you do not want to view any actitivies, you may simply choose the number for exit to end the program." << endl;

    cout << "[1] Activity 1" << endl;
    cout << "[2] Activity 2" << endl;
    cout << "[3] Activity 3" << endl;
    cout << "[4] Activity 4" << endl;
    cout << "[5] Activity 5" << endl;
    cout << "[6} Exit"  << endl;
    cin >> act;

    system("CLS");

    switch(act){
    case 1:
    cout<<"Here are the list of activities in this section." <<endl;
    cout<<"[1.1]Conversion of Celsius to Farenheit" << endl;
    cout<<"[1.2]Conversion of Farenhrit to Celsius:" << endl;
    cout<<"[1.3]Solving the area of the square" << endl;
    cin >> choice;

    system("CLS");
    if(choice == 1 || choice == 1.1){
        cout << "Celsius to Fahrenheit" ;
        cin >> F ;
        F = F*9/5+32;
        cout << F ;
    }

    break;

1 Ответ

0 голосов
/ 17 ноября 2018

Вместо использования значений с плавающей запятой:

int act, choice; //choice is type int -> cannot hold float values or during conversion loss of value 
                 //occurs 1.1 would be 1 as an int. 
float F;

cout<<"[1.1]Conversion of Celsius to Farenheit" << endl;
cout<<"[1.2]Conversion of Farenhrit to Celsius:" << endl;
cout<<"[1.3]Solving the area of the square" << endl;
cin >> choice;

system("CLS");
    if(choice == 1 || choice == 1.1){

Вы можете использовать char для выбора, и может работать так, как ожидалось.

Например:

char choice;

cout<<"[A]Conversion of Celsius to Farenheit" << endl; // changed 1.1 to 'A'
cout<<"[B]Conversion of Farenhrit to Celsius:" << endl; // changed 1.2 to 'B'
cout<<"[C]Solving the area of the square" << endl; // changed 1.3 to 'C'

и ваш оператор if должен соответствовать выбору выбора, например:

if(choice == 'A' || choice == 'a'){

Есть много способов сделать это иначе.

Демо

...