用c++编写一个程序来计算所有可能的方程
Create a program in C++ to calculate all possible equations
我的任务是编写一个c++程序来查找所有可能的带操作符的数学方程。下面是问题:
给定一组数字,例如{5,3,7,3和11}。用+、-、*、/等运算符找出所有可能的数学方程,使其产生给定的答案。例如,5+7-3/3=11。
我需要一个想法如何开始与代码。是蛮力算法吗?我不知道如何交换运算符来创建可能的方程。我不是要求完整的解决方案,只是一个想法如何开始编码。
你可以这样想。+、-、*、/可分别视为1、2、3、4。现在,如果你要尝试所有不同的组合不管你得到的数字数组有多大,你可以这样看。的例子。4数字。
1,1,1,1 1,1,1,2 1,1,1,3 1,1,1,4
1,1,2,1 1,1,2,2 1,1,2,3 1,1,2,4
等等。希望这能有所帮助!
我想声明这不是我最初的想法。我将在下面添加参考。请在下面找到c++代码。
#include <iostream>
#include<string>
using namespace std;
void cntdwn(double sum, double previous, string digits, double target, std::string expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
std::cout<<expr << " = " << target;
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = std::stod(digits.substr(0, i));
string remaining = digits.substr(i);
cntdwn(sum + previous, current, remaining, target, expr + " + " + std::to_string(current));
cntdwn(sum, previous * current, remaining, target, expr + " * " + std::to_string(current));
cntdwn(sum, previous / current, remaining, target, expr + " / " + std::to_string(current));
cntdwn(sum + previous, -current, remaining, target, expr + " - " + std::to_string(current));
}
}
}
void f(string digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
string current = digits.substr(0, i);
cntdwn(0, std::stod(current), digits.substr(i), target, current);
}
}
int main() {
// The digits go as concatenated string
f("5373",11);
return 0;
}
:
5 * 3.000000 - 7.000000 + 3.000000 = 11
引用:
生成添加到目标(Java作业/面试)的所有数学表达式的组合
https://math.stackexchange.com/questions/459857/using-operators-and-4-4-4-4-digits-find-all-formulas-that-would-resolve https://www.careercup.com/question?id=5735906000502784额外注意
a) This code will not make any combinations for the digits. For example if we give (4,4,4,4) as numbers and 10 as target then it will not give any result as the solution in that case should be [(44-4)/4] {this example has been picked from second reference].
b) And this problem is a classic algorithmic problme popularly known as "Countdown Problem" picked from famous UK game.
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址