与'operator*'错误不匹配
No match for 'operator*' error
各位程序员好!
我打算写一个小程序,根据用户输入的小时数和工资来计算不同时间段的总工资。我设法制作了一小部分程序,但当我尝试运行并测试它时,我得到了以下错误:
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提示:pay
是string
,而hours_day
是float
,虽然有些语言允许将字符串与整数相乘,但c++11(或任何其他风格的c)不允许,更不用说允许将字符串和浮点相乘了。
当我试图解决这个问题时,我意识到我已经将pay变量声明为字符串。谢谢大家!这是我犯的一个很小的错误。
您将pay
声明为string
。将其更改为int
或float
,它应该会相乘。类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用于代码的实际运行。
相关文章:
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- 错误:"模板<类_Tp,类_Dp>类 std::unique_ptr"的模板参数列表中参数 1 的类型/值不匹配
- 如何摆脱C++中的枚举不匹配错误?
- 为什么此代码编译 (C++11) 而没有类型不匹配错误
- C++ sigc::mem_fun 中的“呼叫不匹配”错误
- C++ lambda 函数中的“运算符=不匹配”错误
- C++,与"运算符="不匹配...错误
- 将构造函数添加到boost.python子类导致参数不匹配错误
- 基本代码中的"运算符=不匹配"错误
- 运算符重载,但仍然"与运算符不匹配"错误
- C++ - 模板 + 'using' 子句 - 参数不匹配错误
- 模板模板参数 - 类型/值不匹配错误
- 新建/删除运算符不匹配错误的严重程度
- c++代码中的参数不匹配错误
- 类型值与向量不匹配错误
- C++ 运算符不匹配<<错误
- LNK2038,迭代器不匹配错误,需要忽略
- QT5迁移和Boost:if.hp:宏参数不匹配错误
- x11 xGetImage不匹配错误