首页 > 其他分享 >自制计算器

自制计算器

时间:2023-04-30 12:23:31浏览次数:31  
标签:ch nums ++ double 自制 else 计算器 size

自制计算器,拿去参赛了。可以支持普通计算、统计模式。顺便连了个命令提示符。

计算之前需要先输入模式。普通计算是 mode1,统计模式是 mode2,命令提示符是 mode3

例如,输入 mode1 1 + 2 + 3,可以输出 The ans is : 6.00000

输入 mode2 [1, 2, 3]mode2 max,会输出 Maximum : 3.00000

下面是计算器函数:

  • 普通计算模式:

    • + 加法
    • - 减法
    • * 乘法
    • / 除法
    • ^ 幂次
  • 统计模式

    • [1, 2, 3] 初始数据
    • max 返回数据中的最大值
    • min 返回数据中心最小值
    • append 插入数据
    • variance 求方差
    • sum 数据求和
    • average 求数据平均数
  • 命令提示符

    • 与命令提示符中的语句一致。

另外,这个计算器对大小写不敏感。可以使用大写或者小写读入。

如果想要得到更多帮助,可以输入 more 或者 help A。其中 A 是你想要帮助的内容。

计算器代码贴在这。运行以后可以使用。

// Self-Programmed Cauculator. Stronger than most of the Cauculators. 
// Because of Compile needs, all the inputs and outputs were programmed into English.

#include <unordered_map>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <stack>
#include <set>
#define double long double
#define rep(i, a, b) for (int i = (a); i <= (b); i ++ )
#define rop(i, a, b) for (int i = (a); i < (b); i ++ )
#define dep(i, a, b) for (int i = (a); i >= (b); i -- )
#define dop(i, a, b) for (int i = (a); i > (b); i -- )

using namespace std;

using LL = long long;
using PII = pair<int, int>;
using PLL = pair<LL, LL>;
 
// Help Part : Finished
// Cauculating Part : Finished
// Tools Part : Finished
// IOS Part : Finished

namespace TOOLS {
	char turn(char &c) {
		if (c >= 'A' && c <= 'Z') return c;
		else if (c >= 'a' && c <= 'z') return c - 32;
		else return c;
	}
	string turn(string c) {
		for (int i = 0; i < c.size(); i ++ )
			c[i] = turn(c[i]);
		return c;
	}
	string Removed(string c) {
		string s; for (int i = 0; i < c.size(); i ++ )
			if (c[i] != ' ' && c[i] != '\n' && c[i] != '\t' && c[i] != '\r')
				s += turn(c[i]);
		return s;
	}
}
namespace IOS_PART {
	string INPUT() { // Read a String (Without Enter);
		string Str; char ch = getchar();
		while (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') ch = getchar();
		while (ch != '\n' && ch != '\r') Str += ch, ch = getchar();
		return Str;
	}
	void START() { // Restart The Cauculator
		system("cls");
		puts("============================= Self-Programmed Cauculator. Developed by Li Chengyue. =============================");
		puts("Because of Compile needs, all the inputs and outputs were programmed into English."); system("pause");
		puts("Three Modes has been programmed into the cauculator. ");
		puts("\t mode1 : normal cauculating mode. Programmed for normal compute. ");
		puts("\t mode2 : statistical cauculating mode. Programmed for sequences. ");
		puts("\t mode3 : system mode. Programmed for system operation. (connected to command prompt). ");
		puts("You need to add the mode you use before type in an expression. ");
		puts("For example : ");
		printf("\t mode1 (1 + 2) ^ 3\n");
		printf("\t mode2 [1, 2, 3, 4]\n");
		printf("\t mode2 max\n");
		printf("\t mode3 dir\n");
		puts("PLEASE PAY ATTENTION : The cauculator are NOT case sensitive. Both 'MODE 1' and 'mode 1' are OK");
		puts("You can type 'help' to get more information. For example, type in 'help mode1' for more information about mode1.");
		system("pause");
		puts("Want more examples? Type in 'more' ! ");
	}
	
	void OUTPUT(string &Str) { // Put out a String
		for (int i = 0; i < Str.size(); i ++ )
			putchar(Str[i]);
		if (*Str.end() != '\n') puts(""); // Out Put Extra Enter;
	}
}
namespace HELP_PART {
	void HELP(string Str) {
		if (Str == "MODE1") {
			printf("Normal Cauculator. ");
			puts("You can use an expression containing addition('+'), subtraction('-'), multiplication('*'), division('\') and square('^'). ");
			puts("For example, you can use the expression like '(1 + 2) ^ 3 * 5'. The cauculator will tell you the answer. ");
		}
		else if (Str == "MODE2") {
			printf("Statistical Cauculator. ");
			puts("Use [a, b, c...] to input a array. ");
			puts("Use 'append' to push a number in to the array, such as 'append 1'");
			puts("Use 'min' to query the minimum of the array. ");
			puts("Use 'max' to query the maximun of the array. ");
			puts("Use 'sum' to query the sum of the array. ");
			puts("Use 'average' to query the average of the array. ");
			puts("Use 'variance' to query the variance of the array. ");
		}
		else if (Str == "MODE3") {
			puts("System Cauculator. ");
			puts("Use it for system operation. "); system("help");
		}
		else if (Str == "MAX") { puts("Get the Maximum of an array. Used in 'mode2'"); }
		else if (Str == "MIN") { puts("Get the Minimum of an array. Used in 'mode2'"); }
		else if (Str == "AVERAGE") { puts("Get the average of an array. Used in 'mode2'"); }
		else if (Str == "VARIANCE") { puts("Get the variance of an array. Used in 'mode2'"); }
		else if (Str == "SUM") { puts("Get the Sum of an array. Used in 'mode2'"); }
		else { puts("Incorrect command syntax. "); }
	}
}
namespace Normal_Cauculate {
	stack<double> nums; 
	stack<char> op;
	unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'^', 2}};
	void eval() {
		double a = nums.top(); nums.pop();
		double b = nums.top(); nums.pop();
		char p = op.top(); op.pop();
		if (p == '+') nums.push(a + b);
		else if (p == '-') nums.push(b - a);
		else if (p == '*') nums.push(a * b);
		else if (p == '^') nums.push(pow(b, a));
		else nums.push(b / a);
	}
	void CAUCULATE(string ch) {
		while (op.size()) op.pop();
		while (nums.size()) nums.pop();
		int f = 1;
		for (int i = 0; i < ch.size(); i ++ ) {
			if (ch[i] == '-' && (i == 0 or ch[i - 1] == '(')) {
				f = -1; continue;
			}
			if (isdigit(ch[i])) { // Push in a number;
				double x = 0; int j = i;
				while  (j < ch.size() and isdigit(ch[j]))
					x = x * 10 + (ch[j] ^ 48), j ++ ;
				if (ch[j] == '.') {
					double now = 0.1; j ++ ;
					while (j < ch.size() and isdigit(ch[j]))
						x = x + now * (ch[j] ^ 48), now /= 10.00, j ++ ;
				}
				nums.push(x * f); i = j - 1;
			}
			else if (ch[i] == '(') op.push(ch[i]);
			else if (ch[i] == ')') {
				while (op.top() != '(')
					eval();
				op.pop();
			}
			else if (ch[i] == '+' or ch[i] == '-' or ch[i] == '*' or ch[i] == '/' or ch[i] == '^') {
				while (op.size() && h[op.top()] >= h[ch[i]])
					eval();
				op.push(ch[i]);
			}
			f = 1;
		}
		while (op.size()) eval();
		printf("The ans is : %.5Lf\n", nums.top());
	}
}
namespace Statistical_Part {
	multiset<double> nums;
	void append(double x) { nums.insert(x); }
	double Max() { auto it = nums.end(); it -- ; return *it; }
	double Min() { return *nums.begin(); }
	void CAUCULATE(string ch) {
		nums.clear();
		int f = 1;
		for (int i = 0; i < ch.size(); i ++ ) {
			if (ch[i] == '-') { f = -1; continue; }
			if (isdigit(ch[i])) {
				double x = 0; int j = i;
				while  (j < ch.size() and isdigit(ch[j]))
					x = (x * 10) + (ch[j] ^ 48), j ++ ;
				if (ch[j] == '.') {
					double now = 0.1; j ++ ;
					while (j < ch.size() and isdigit(ch[j]))
						x = x + now * (ch[j] ^ 48), now /= 10.00, j ++ ;
				}
				append(x * f); i = j - 1;
			}
			f = 1;
		}
	}
	void APPEND(string ch) {
		double x = 0, f = 1;
		for (int i = 0; i < ch.size(); i ++ ) {
			if (ch[i] == '-') f = -1;
		    if (isdigit(ch[i])) {
				int j = i;
				while  (j < ch.size() and isdigit(ch[j]))
					x = (x * 10) + (ch[j] ^ 48), j ++ ;
				if (ch[j] == '.') {
					double now = 0.1; j ++ ;
					while (j < ch.size() and isdigit(ch[j]))
						x = x + (double)now * (ch[j] ^ 48), now /= 10.00, j ++ ;
			    }
			    i = j - 1;
		    }
		}
		append(x * f);
	}
	double Sum() {
		double sum = 0;
		for (auto i = nums.begin(); i != nums.end(); i ++ )
			sum += *i;
		return sum;
	}
	double Average() {
		double sum = Sum();
		return (double)sum / nums.size();
	}
	double variance() {
		double ave = Average(), sum = 0;
		for (auto i = nums.begin(); i != nums.end(); i ++ )
			sum += (double)(*i - ave) * (*i - ave);
		return (double)sum / nums.size();
	}
}
void SYSTEM(string ch) {
	const char *p = ch.data();
	system(p);
}
bool contain(string ch, string tmp) {
	for (int i = 0; i < tmp.size(); i ++ )
		if (ch[i] != tmp[i]) return false;
	return true;
}
void MAIN() {
	IOS_PART::START();
	while (true) {
		string ch = IOS_PART::INPUT(), Str = ch; ch = TOOLS::Removed(ch);
		if (contain(TOOLS::Removed(ch), "HELP")) HELP_PART::HELP(ch.substr(4)); // Get More Help
		else if (contain(ch, "EXIT")) { puts("Thanks for Using!") , exit(0); } // Break Out From the Cauculator
		else if (contain(ch, "START")) { MAIN(); exit(0); } // Rebuild The Cauculator
		else if (contain(ch, "MODE1")) Normal_Cauculate::CAUCULATE(ch.substr(5));
		else if (contain(ch, "MODE3")) { SYSTEM(Str.substr(Str.find("3") + 1)); }
		else if (contain(ch, "MORE")) {
			puts(""); puts("example 1 :\n\t mode1 (1 + 2) * 3"); puts("\t The ans is : 9.00000 \n");
			puts("example 2 :\n\t mode1 2 / (2 ^ 3)"); puts("\t The ans is : 0.25000\n");
			puts("example 3 :\n\t mode2 [1, 2, 3]\n\t mode2 max"); puts("\t Maximum : 3.00000\n");
			puts("example 4 :\n\t mode3 cls\n\t The screen will be clear. ");
		}
		else {
			ch = ch.substr(5);
			if (ch[0] == '[') Statistical_Part::CAUCULATE(ch);
			else if (ch.substr(0, 3) == "MAX") printf("Maximum : %.5Lf\n", Statistical_Part::Max());
			else if (ch.substr(0, 3) == "MIN") printf("Minimum : %.5Lf\n", Statistical_Part::Min());
			else if (ch.substr(0, 6) == "APPEND") Statistical_Part::APPEND(ch.substr(6));
			else if (ch.substr(0, 8) == "VARIANCE") printf("Variance : %.5Lf\n", Statistical_Part::variance());
			else if (ch.substr(0, 3) == "SUM") printf("Sum : %.5Lf\n", Statistical_Part::Sum());
			else if (ch.substr(0, 7) == "AVERAGE") printf("Average : %.5Lf\n", Statistical_Part::Average());
		}
	}
}

signed main() {
	MAIN(); system("pause");
	return 0;
}

标签:ch,nums,++,double,自制,else,计算器,size
From: https://www.cnblogs.com/LcyRegister/p/17365109.html

相关文章

  • [oeasy]python0141_自制模块_module_reusability_复用性
    自制包内容回忆上次内容上次导入了外部的py文件importmy_module导入一个自己定义的模块 可以使用my_module中的变量不能直接使用my_module.py文件中的变量只要加my_module.作为前缀就可以  直接导入导入变量、函数frommy_mo......
  • 五、自制代码生成器提高开发效率
    主要内容以乘车人增删改查为模板,自制单表管理,前后端生成器。学习代码生成器原理,学习freemarker。写自己的生成器,可用于导出复制excel,页面静态化等。代码生成器的底层原理生成器原理:使用freemarker,利用模板,生成java、vue等项目文件。freemarker是老牌模板引擎,以前常用于页......
  • 我问ChatGPT要了个写计算器的代码,结果翻车了
    大家好,我是皮皮。一、前言ChatGPT最近非常火爆,很多人都在玩。前几天在Python最强王者交流群【孤独】找ChatGPT要了一个用Python实现计算器的代码,这里拿出来给大家分享下。下面的代码是ChatGPT给出的:#导入PyQt5模块fromPyQt5.QtWidgetsimportQApplication,QWidget,QGridLayou......
  • 简单的计算器(函数版)
    """简单的计算器这是一个简单的计算器,可以进行加、减、乘、除四种运算。代码如下:"""#简单的计算器#加法defadd(a,b):returna+b#减法defsub(a,b):returna-b#乘法defmul(a,b):returna*b#除法defdiv(a,b):ifb==0:return"除......
  • 简单的计算器
    perators={"+":lambdax,y:x+y,"-":lambdax,y:x-y,"*":lambdax,y:x*y,"/":lambdax,y:x/y}op=input("请输入运算符(+、-、*、/):")num1=float(input("请输......
  • 面积计算器(函数重载)
    一.问题描述:实现一个计算器,能够计算矩形或长方形的面积;二.编程思路:1.定义area函数2.定义主函数3.设立for循环4.设定if选择结构三.代码实现:#include<iostream>#include<string>usingnamespacestd;intarea(int,int);intarea(int,int,int);intmain(){inti,......
  • 自制操作系统 (大二寒假)
    这是最后的效果图,可以在实体机上面运行。功能:运行app,app调用自己写的api实现输出字符串终端输入输出界面计时器支持鼠标,键盘问题:实体机鼠标有问题介绍:系统完全参考haribote,算是精简版或者二开的haribote,去除了GUI界面,终端界面完全自己开发,这是......
  • android studio 简易计算器制作
    只是记录一下代码,随意取用<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width=&quo......
  • c# 计算器2.0源码
      主要时间浪费在 //执行计算objectresult=newDataTable().Compute(s,"");这条语句上。如果不加处理,特别大的整数相乘,会提示值太大。只好将整数加个0变为小数;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;......
  • 算法刷题-阶乘后的零(数学)、模拟计算器(算法初阶、基础知识)、解码方法(字符串、动态
    阶乘后的零(数学)给定一个整数n,返回n!结果中尾随零的数量。提示n!=n*(n-1)*(n-2)*...*3*2*1示例1:输入:n=3输出:0解释:3!=6,不含尾随0示例2:输入:n=5输出:1解释:5!=120,有一个尾随0示例3:输入:n=0输出:0提示:0<=n<=104**进阶:**你......