C语言计算器
本帖最后由 juhugufudu 于 2020-3-17 09:58 编辑/*
这个代码是输入以下的式子,如:
4565+987*989/9/9/9/9/9/852*987-965
但你可以把代码改一下,改成double,也可以写成这样:
输入:
5+9*8
输出:
5+9*8
=5+72
=77
输出 运算结果
*/
#include<stdio.h>
#include<string.h>
char s;
long int num = {0};
char chs;
int length, x = 1;
void move(int start,int ins)
{
int i, j, k;
for(i = start;i<length;i++) num = num;
num = ins;
for(j = start+1;j<length;j++) chs = chs;
//for(i = 0;i<length-1;i++) printf("%ld ",num);
//printf("\n");
//printf("%s\n",chs);
length -= 1;
}
long int f(int a, int b,char ch)
{
switch(ch)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return (int)a/b;
}
}
void init()
{
// 把 s 分成 num,chs
int i, index = 0;
for(i = 0;i<length;i++)
{
if(s>='0' && s<='9')
num = num*10+(s - '0');
else
{
chs = s;
index += 1;
}
}
length = index+1;
}
int main()
{
int i, temp = 0;
char ch;
scanf("%s",s);
length = strlen(s);
//printf("%d\n\n", length);
if(s == '-') chs = '-';
else chs = '+';
init();
for(i = 0;i<length;i++)
{
ch = chs;
if(ch == '*' || ch == '/')
{
temp = f(num,num,ch);
move(i - 1, temp);
i -= 1;
}
}
for(i = 1;i<length;i++)
{
ch = chs;
if(ch == '+' || ch == '-')
{
temp = f(num,num,ch);
move(i - 1, temp);
i -= 1;
}
}
printf("%ld\n",num);
return 0;
}
回复即可看到真正的答案....
#include <stdio.h>
#include <stdlib.h>
static int calculator(char *s)
{
int n;
int pos1 = 0;
int pos2 = 0;
int *nums = malloc(100 * sizeof(int));
char *signs = malloc(100 * sizeof(char));
nums = 0;
while (*s != '\0') {
switch (*s) {
case '+':
case '-':
if (pos1 >= 3) {
int b = nums;
int a = nums;
if (signs[--pos2] == '+') {
nums = a + b;
} else {
nums = a - b;
}
pos1--;
}
case '*':
case '/':
signs = *s;
break;
case ' ':
break;
default:
n = 0;
while(*s >= '0' && *s <= '9') {
n = n * 10 + (*s - '0');
s++;
}
s--;
if (pos1 >= 2 && signs != '+' && signs != '-') {
int a = nums[--pos1];
if (signs[--pos2] == '*') {
n = a * n;
} else {
n = a / n;
}
}
nums = n;
break;
}
s++;
}
while (pos2 > 0) {
n = nums[--pos1];
int a = nums[--pos1];
if (signs[--pos2] == '+') {
n = a + n;
} else {
n = a - n;
}
}
return n;
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test string\n");
exit(-1);
}
printf("%d\n", calculator(argv));
return 0;
}
看看 太难了太难了看看大佬怎么写的 加求余,指数幂等功能应该怎样呢 优秀 学习学习 研究一下 谢谢
来看看。。。。。。 sddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd 好奇 ok 1 学习 了解一下 我来看看 冲冲冲 666 {:10_257:} calculator函数中,pos1= 0;pos2 = 0;后面没有改变这两个变量的值,if语句中怎么判断pos1 >= 3? 且num 是什么?这些不理解,望能回复,感谢。
页:
[1]
2