doupian9490 2013-09-14 16:14
浏览 46
已采纳

如何在另一个IF语句中使用IF语句来解决复杂的计算

The question is taken from http://www.programmr.com/node/137861/begin and you can test it there.

I am writing a program which displays an appropriate name for a person, using a combination of nested if's and compound conditions. Ask the user for a gender, first name, last name and age.

If the person is female and 20 or over, ask if she is married. If so, display "Mrs." in front of her name. If not, display "Ms." in front of her name. If the female is under 20, display her first and last name.

If the person is male and 20 or over, display "Mr." in front of his name. Otherwise, display his first and last name.

Note that asking a person if they are married should only be done if they are female and 20 or older.

Here is my code:

<?php
$finalName;
echo "What is your Gender (M or F):";
$gender = trim(fgets(STDIN));
echo "First Name:";
$firstName = trim(fgets(STDIN));
echo "Last Name:";
$lastName = trim(fgets(STDIN));
echo "Age:";
$age = trim(fgets(STDIN));

if ($gender == "M" and $age>19) {
    $finalName = "Mr. ".$lastName;
}

if ($age<20) {
    $finalName = $firstName.$lastName;
}

if ($gender == "F" and $age>19) {
    echo "Are you married:";
    $married = trim(fgets(STDIN));

    if ($married == "Y") {
        $finalName = "Mrs. ".$lastName;
    }
    else {
        $finalName = "Ms. ".$lastName;
    }
}

echo "Then I will call you ".$finalName;
exit;
?>

The code does not give expected output. Is there something wrong in the logic or does if statement not work this way ?

  • 写回答

1条回答 默认 最新

  • duanjian5059 2013-09-14 16:53
    关注

    Finally this is what worked. I replaced = with == in the if statement.

    I also replace "and" with "&&" in the if statement and it worked like a charm.

         if ($gender == "M" && $age>19) {
        $finalName = "Mr. ".$lastName;
    }
    
    if ($age<20) {
        $finalName = $firstName." ".$lastName;
    }
    
    if ($gender == "F" && $age>19) {
        echo "Are you married:";
        $married = trim(fgets(STDIN));
    
        if ($married == "Y") {
            $finalName = ("Mrs. ".$lastName);
        }
        else {
            $finalName = ("Ms. ".$lastName);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法