与'operator*'错误不匹配

No match for 'operator*' error

本文关键字:不匹配 错误 operator      更新时间:2023-10-16

各位程序员好!

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

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();
}

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

@101010提示:paystring,而hours_dayfloat,虽然有些语言允许将字符串与整数相乘,但c++11(或任何其他风格的c)不允许,更不用说允许将字符串和浮点相乘了。

当我试图解决这个问题时,我意识到我已经将pay变量声明为字符串。谢谢大家!这是我犯的一个很小的错误。

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

您可以根据以下内容更新程序代码以解决问题正如Scott所建议的,您将输入作为字符串,并尝试将其与浮点相乘,这是不可能的。您需要将输入作为浮点值,这样一切都可以工作。

#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用于代码的实际运行。