如何在if语句中执行公式

时间:2018-11-17 12:42:29

标签: c++ if-statement switch-statement

我想让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 :(得分:0)

代替浮点值:

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'){

有很多方法可以完成此操作。

Demo