不匹配'运营商*'错误

时间:2015-06-22 20:28:39

标签: c++ c++11

Hello其他程序员!

我打算用一个小程序来计算不同时段的总工资,具体取决于用户输入的小时数和工资。我设法制作了一小部分程序但是当我尝试运行它并测试它时,我收到以下错误:

Line 33: error: no match for 'operator*' in 'pay * hours_day'

我尝试对这个问题进行谷歌搜索,但我真的很困惑导致它的原因。

这是我的完整程序代码:

#include <iostream>
#include <random>
#include <time.h>
#include <cstdlib>
#include <string>

using namespace std;

/*

*Program Flowchart*

- Find out how much a worker gets paid per hour, and then find out how many hours they work
a day, and then multiply that to get the total pay in a week or a month or a year.

*/

// global variables

string pay;
float hours_day;


// function that takes the amount of money and calculates the total pay in a week
int total_pay_week() {
    cout << "Type in your salary per hour." << endl;
    cin >> pay;
    cout << "Ok, how many days do you work per day?" << endl;
    cin >> hours_day;

    float total_day = pay * hours_day;

    float total_week = total_day * 7;

    cout << "Your total pay in a week is " << total_week << "if you worked " << hours_day << " per day. " << endl;

}


int main() {

    total_pay_week();

}

这是我程序的早期版本!我只是想知道导致这个问题的原因。

4 个答案:

答案 0 :(得分:1)

正如@ 101010提示:paystring,而hours_dayfloat,而有些语言允许您将字符串与整数相乘,c + +11(或任何其他c的味道)不会,更不用说允许字符串和浮点数相乘。

答案 1 :(得分:1)

我意识到我将pay变量声明为字符串,因为我试图解决这个问题。谢谢大家!这是我的一个非常无意义的错误。

答案 2 :(得分:0)

您将pay声明为string。将其更改为intfloat,它应该相乘。类std::string没有此算术的*运算符,因此可以解释错误文本。

答案 3 :(得分:0)

您可以按照以下更新程序代码来解决问题 正如斯科特建议你将输入作为字符串并尝试将其乘以浮点而这是不可能的。你需要把输入作为浮点数,一切都会有效。

#include <iostream>
#include <random>
#include <time.h>
#include <cstdlib>
#include <string>

using namespace std;

/**
 * *Program Flowchart*
 *
 * - Find out how much a worker gets paid per hour, and then find out how many hours they work
 *   a day, and then multiply that to get the total pay in a week or a month or a year.
 */

// global variables

float pay;
float hours_day;


// function that takes the amount of money and calculates the total pay in a week
int total_pay_week()
{
    cout << "Type in your salary per hour." << endl;
    cin >> pay;
    cout << "Ok, how many days do you work per day?" << endl;
    cin >> hours_day;

    float total_day = pay * hours_day;

    float total_week = total_day * 7;

    cout << "Your total pay in a week is $" << total_week << " as you are working " << hours_day << " hours per day. " << endl;

}

int main()
{
    total_pay_week();
}

结帐https://ideone.com/mQj3mh以了解代码的实际运行情况。