You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

科学计算器算术函数输出格式混乱,如何修复?

科学计算器算术输出格式错误排查与修复

我正在开发一款科学计算器,但算术函数的输出显示不符合预期。无法找出为何会出现多余的括号、逗号导致输出错乱,且最终计算结果还会重复显示。

相关代码

import math
import random

class Calculator():
    
    def __init__(self):
        
        self.functions = {
            'sin': math.sin,
            'cos': math.cos,
            'tan': math.tan,
            'log': math.log,
            'factorial': math.factorial,
            'exp': math.exp,
            'sqrt': math.isqrt,
            'acos': math.acos,
            'asin': math.asin,
            'atan': math.atan,
            'rand': random.randrange,
            
            }

        self.constants = {'pi': math.pi,
                          'e': math.e
        }

class Arithmetic(Calculator):
    
    def __init__(self, *args):
        super().__init__()
        self.args = args
        

    def print_format(self, numbers, operator, result):
        
        width = max(len(str(n)) for n in (list(numbers) + list(result))) + 2 #select max width from numbers or answer

        lines = []
        lines.append(f'{str(numbers[0]).rjust(width)}') #first number

        #subsequent numbers
        for n in str(numbers[1:]):
            lines.append(f'{operator}{n.rjust(width-1)}')
        
        dashes = '-' * width
        lines.append(dashes)
        lines.append(f'{str(result).rjust(width)}')

        return '\n'.join(lines)



    def add(self, *args):
        answer = sum(self.args)
        str_answer = str(answer)
        print(self.print_format(self.args, '+', str_answer))
        return str_answer
    

    def __str__(self):
        pass


test = Arithmetic(23,2,3)
print(test.add())

实际输出

23
+  (
+  2
+  ,
+   
+  3
+  )
----
  28
28

期望输出

23
+  2
+  3
----
  28

错误点与修复方案

1. 遍历逻辑错误导致多余字符

你在print_format方法里遍历的是str(numbers[1:]),而numbers[1:]是元组(2,3),转成字符串后会变成"(2, 3)",遍历这个字符串会逐个取出每个字符(包括括号、逗号、空格),这就是错乱行的来源。

修复:直接遍历numbers[1:]中的元素,不要转成字符串:

# 替换原循环代码
for n in numbers[1:]:
    lines.append(f'{operator}{str(n).rjust(width-1)}')

2. 结果重复输出

add方法内部已经调用print输出了格式化内容,而你调用print(test.add())时,又会打印add返回的str_answer,导致结果被输出两次。

修复二选一:

  • 去掉add方法里的print,调用时用print(test.add());
  • 保留add里的print,调用时直接写test.add(),不要套print(推荐此方案)。

修改后的调用代码:

test = Arithmetic(23,2,3)
test.add()

3. 宽度计算逻辑错误

print_format里的list(result)会把字符串result拆成单个字符的列表(比如"28"会变成['2','8']),导致计算最大宽度时出错。

修复:把list(numbers) + list(result)改成list(numbers) + [result]:

width = max(len(str(n)) for n in (list(numbers) + [result])) + 2

最终修正后的完整代码

import math
import random

class Calculator():
    
    def __init__(self):
        
        self.functions = {
            'sin': math.sin,
            'cos': math.cos,
            'tan': math.tan,
            'log': math.log,
            'factorial': math.factorial,
            'exp': math.exp,
            'sqrt': math.isqrt,
            'acos': math.acos,
            'asin': math.asin,
            'atan': math.atan,
            'rand': random.randrange,
        }

        self.constants = {'pi': math.pi,
                          'e': math.e
        }

class Arithmetic(Calculator):
    
    def __init__(self, *args):
        super().__init__()
        self.args = args
        

    def print_format(self, numbers, operator, result):
        # 修正宽度计算逻辑
        width = max(len(str(n)) for n in (list(numbers) + [result])) + 2

        lines = []
        lines.append(f'{str(numbers[0]).rjust(width)}')

        # 修正遍历逻辑
        for n in numbers[1:]:
            lines.append(f'{operator}{str(n).rjust(width-1)}')
        
        dashes = '-' * width
        lines.append(dashes)
        lines.append(f'{str(result).rjust(width)}')

        return '\n'.join(lines)



    def add(self, *args):
        answer = sum(self.args)
        str_answer = str(answer)
        print(self.print_format(self.args, '+', str_answer))
        return str_answer
    

    def __str__(self):
        pass


test = Arithmetic(23,2,3)
test.add()

运行后即可得到符合预期的输出。

内容的提问来源于stack exchange,提问作者new_coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 08:28:14