简体   繁体   English

向我的函数添加 If 语句

[英]Adding an If statement to my function

Just began coding and have an assignment that prompts the user to enter "wage" and "hours" then calculate.刚刚开始编码并有一个任务,提示用户输入“工资”和“小时”然后计算。 We're beginning to use functions and I wrote a code that calls the code, but I get an error saying my if statement in the function will never be executed.我们开始使用函数,我编写了一个调用该代码的代码,但是我收到一个错误消息,说我在函数中的 if 语句永远不会被执行。 Here's the code below:这是下面的代码:

#include <iostream>
#include <iomanip>
using namespace std;

float calcwage (float h, float w);

int main()
{
    float wage, hours, totwage;
    cout << setiosflags(ios::fixed|ios::showpoint)
    << setprecision(2);
    cout << "Enter hours worked: ";
    cin >> hours;
    cout << "Enter hourly wage:$ ";
    cin >> wage;
    totwage = calcwage (hours, wage);
    cout <<"Total wages=$ " << totwage << "\n";
    return 0;
}

float calcwage (float h, float w)
{
    return h * w; if(h <= 40)
        ;
    return (h * (w * 1.5)); if(h > 40)
        ;
}

Are if statements not allowed in functions?函数中不允许使用 if 语句吗? I'm confused and am not sure how my code can return back to main.我很困惑,不确定我的代码如何返回主程序。

Your if statements need to be before the return statements.您的 if 语句需要在 return 语句之前。

Also you only need on if statement since there are only two options.此外,您只需要 if 语句,因为只有两个选项。 If the first one doesn't get hit than no need to check the other option as its the only other option.如果第一个没有被击中,则无需检查另一个选项作为唯一的其他选项。

if(h <=40) return h*w; if(h <=40) 返回 h*w;

return h*w*1.5返回高*宽*1.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM