标题:写计算机
取消只看楼主
seahdiao
Rank: 1
来 自:马来西亚
等 级:新手上路
帖 子:20
专家分:0
注 册:2020-3-19
结帖率:100%
已结贴  问题点数:20 回复次数:0 
写计算机
假期得空想练练手写计算机,我的思路是用户写一个算式,如“2-3-4+45-34+23”,然后这程序就帮忙算出来。请问大佬,以下的代码要如何改进才能让计算机懂得先加减后乘除和能先做()里面的内容。如果以下方法实现不了,也请大佬提供下思路。

void main() {
    char input[100];
    int count = 0;
    int  y,total;
    char operation;
    FILE *fptr;
   
    printf("Enter a equation without \"=\" >");
    scanf("%s", &input);
    rewind(stdin);

    fptr = fopen("a.txt", "w");
    if (fptr != 0) {
        printf("\n\nopen a.txt sucess\n\n");
    }
    else {
        printf("\n\n open a.txt error\n\n");
    }


    fprintf(fptr,"%s",input);
    printf("prntf to a.txt success\n\n");
    fclose(fptr);

    fptr = fopen("a.txt", "r");
    if (fptr != 0) {
        printf("open a.txt for read success\n\n");

    }
    else {
        printf("Error to read a.txt\n\n");
    }


    while (!feof(fptr)) {
        if (count == 0) {
            fscanf(fptr,"%d", &total );
        }
        else {
            fscanf(fptr,"%c%d", &operation, &y);
            if (operation == '+') {
                total = total + y;
            }
            else if (operation == '-') {
                total = total - y;
            }
            else if (operation == '*') {
                total = total * y;
            }
            else if (operation == '/') {
                total = total / y;
            }
        }
        count++;

    }

    fclose(fptr);
    fptr = fopen("history.txt", "a");
    fprintf(fptr,"%s=%d", input, total);
    printf("\n\nAns:%s=%d\n\n", input, total);

    system("pause");


}
搜索更多相关主题的帖子: printf operation 计算机 input txt 
2020-05-09 12:10



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-501510-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.082189 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved