c++ - 无效的操作数和非法赋值强制转换
问题描述
该程序的目的是获取一个美元金额并打印将返回的钞票数量,以最有效地提供该金额和剩余的零钱。(即 523.33 美元 = 50 美元 x 10 / 20 美元 x1 / 1 美元 x 3/ .33 剩余)。除了我在附加图像中遇到的错误外,它应该可以工作。我已经尝试了我被教导的每一次铸造,但没有任何效果。
#include <iostream>
using namespace std;
int main()
{
double withdrawAmount; //declare variable to store use input for desired withdraw amount
do { //Ask for valid user input
cout << "Please enter an amount to withdraw from yor account" << endl;
cin >> withdrawAmount; //save user input into withdrawAmount variable
} while (withdrawAmount < 1);
//Print greatest # of bills that can be taken from the withdrawlAmount
cout << "$50 bills :"<< (int) withdrawAmount / 50 << endl;
//Print number of $50 bills
(int) withdrawAmount %= 50;
cout << "$20 bills: " << (int) (withdrawAmount %= 50) / 20 << endl;
//Print number of $20 bills
(int) withdrawAmount %= 20;
cout << "$10 bills: " << (int) (withdrawAmount %= 20) / 10 << endl;
//Print number of $10 bills
(int)withdrawAmount %= 10;
cout << "$5 bills: " << (int) (withdrawAmount %= 10) / 5 << endl;
//Print number of $5 bills
(int)withdrawAmount %= 5;
cout << "$1 bills: " << (int) (withdrawAmount %= 5) / 1 << endl;
//Print number of $1 bills
(int) withdrawAmount %= 1;
cout << "Remaining: " << withdrawAmount / 1 << endl;
return 0;
}
解决方案
(int) withdrawAmount %= 50;
应该替换为
withdrawAmount = std::fmod(withdrawAmount, 50);
其他值也一样。(不要忘记#include <cmath>
)。
作为替代方案:
double input; //declare variable to store use input for desired withdraw amount
do { //Ask for valid user input
cout << "Please enter an amount to withdraw from yor account" << endl;
cin >> input; //save user input into withdrawAmount variable
} while (input < 1);
int withdrawAmount = input; // rounded toward 0.
std::cout << "$50 bills :"<< withdrawAmount / 50 << std::endl;
withdrawAmount %= 50;
// And so on...
// Final remaining
std::cout << "Remaining: " << input - int(input) << std::endl;
推荐阅读
- c# - 提高大型项目 c# WPF XAML 中的性能
- mysql - 在分数表中获得排名
- python - IMAP4.search 按主题名称 python
- javascript - 如何映射 SetState 函数?
- javascript - 如何在 lightgallery 上添加自定义触发器?
- assembly - 为什么需求 rfo offcore 响应 /offcore 请求太多?
- sql - Cognos Report Studio 版本 10.2.1 中格式化日期提示的问题
- android - 关于我的片段和活动的奇怪行为
- r - R - 分别对每个变量使用求和或对所有变量求和的差异
- php - 数据模型 Laravel(旅游管理)