本文介绍了C ++简单计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我试图制作一个C ++计算器来自动解算计算。我有一个字符串/ char *,格式为例如1 + 1,我希望它能解决计算并显示它。



Hi im trying to make a C++ calculator to auto solve a calculation. I have a string/char* that is in the format of e.g 1+1 and i would like it to solve the calculation and display it.

int main()
{
	char input[] = "3+2";
	float num1, num2;
	char operation;

	printf("%c \n", input[0]);
	printf("%c \n", input[1]);
	printf("%c \n", input[2]);

	num1 = input[0];
	operation = input[1];
	num2 = input[2];
	//printf("Enter operator either + or - or * or divide : ");
	//scanf("%c", &operation);
	//printf("Enter two operands: ");
	//scanf("%f%f", &num1, &num2);
	if (operation == '+')
			printf("%.1f + %.1f = %.1f\n", num1, num2, num1 + num2);
		if (operation == '-')
			printf("=%f\n", num1 - num2);
		if (operation == '*')
			printf("=%f\n", num1*num2);
		if (operation == '/')
			printf("=%f\n", num1 / num2);
	system("pause");
	return 0;
}





输出



Output

3
+
2
51.0 + 50.0 = 101.0
Press any key to continue . . .





它将输入数字作为ASCII等价物然后添加它们我需要在计算发生之前转换数字,例如char如果是这样的话我怎么做而不转换整个字符?



我尝试过:



将单独的字符转换为浮点数:



char * input =3 + 2;



float num1 = atof(input [0]);

float num2 = atof(input [2]);



Its taking the input numbers as the ASCII equivalent and then adding them do i need to convert the numbers before the calculation takes place e.g char to float if so how do i do that without converting the entire char?

What I have tried:

Converting separate chars to floats:

char* input = "3+2";

float num1 = atof(input[0]);
float num2 = atof(input[2]);

推荐答案


#include <stdio.h>
#include <stdlib.h>

int main()
{
    char text[] = "123.0+456.0";
    char *cursor = text;
    double term1 = strtod(cursor, &cursor);
    char op = *cursor++;
    if (!op)
        return 2;
    double term2 = strtod(cursor, &cursor);
    double result = 0.f;
    switch (op)
    {
        case '+':
            result = term1 + term2;
            break;
        case '-':
            result = term1 - term2;
            break;
        case '*':
            result = term1 * term2;
            break;
        case '/':
            result = term1 / term2;
            break;
        default:
            return 1;
    }
    printf("%f%c%f=%f\n", term1, op, term2, result);
    return 0;
}





此代码旨在表达一个想法 - 不是一个完整的解决方案。它不考虑除零,空格或更复杂的表达式。我希望它能带领你走向更好的方向。



This code is meant to express an idea - not be a complete solution. It does not consider divide by zero, white space, or more complex expressions. I hope it leads you in a better direction.


这篇关于C ++简单计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:38
查看更多