这道题展示了函数内外有同名变量时,各语言有什么不同。 除克雷康外的七种语言的解答,把外面的一天销售额和函数里的小票合计都命名为 total。 像JS・TS的 let total = 0;、Java・C#・C・C++的 int total = 0; 那样在函数里重新声明,就会得到一个遮住外面 total 的局部变量;它每次调用都重新创建,函数结束就消失。 外面的 total 在JS・TS里是最上层的 let,在Java・C#里是 static 字段,在C・C++里是全局变量。 Python没有专门用来声明的关键字,所以只要在函数里像 total = 0 这样赋值,这个名字在整个函数里就成了局部变量。 克雷康正好相反:在函数里给最上层已有的名字赋值,会改变外面的变量,而且除了参数以外,没有办法另建一个同名的局部变量。 所以克雷康的解答把外面的变量叫 销售额,函数里的变量叫 合计,名字分开。 在函数外使用函数里第一次创建的 合计 是编译错误。 陷阱一:把小票合计放在函数外面,每次调用时它不会回到0。 前面小票的合计会一直累加,例1的输出变成 4500、5300、8200、18000。 陷阱二:在函数里不声明就写 total = 0;,不会产生新变量,而是赋值给外面的 total。 JS・TS・Java・C#・C・C++都不报错,照样运行。 在克雷康里把函数里的合计也叫 销售额,结果一样。 每算一张小票的合计,一天的销售额就被这个合计覆盖,再加上一次返回的合计,所以例1的最后一行是 5800(2900 + 2900)而不是 8200。 不过在JS・TS・Java・C#里写成一行 total += receiptTotal(…) 时,会在调用函数之前先读出 total 的值,所以这个错误不会在输出里显现。 只是没显现,代码仍然是错的。 陷阱三:在Python里想在函数中给外面的 total 加值而写 total += s,由于这个函数里有给 total 赋值的语句,total 就成了局部变量,读取尚未赋值的它会以 UnboundLocalError 停止。 要在函数里修改外面的变量,必须先写 global total。 像这个解答那样返回合计、由调用方相加,就不需要 global。
Pythonmain.py · 25 行
import sys# 하루 매출: 함수 밖(맨 위)에 둔 변수total = 0def receipt_total(prices): # 함수 안에서 값을 넣으면 Python은 그 이름을 지역 변수로 만든다. # 그래서 이 total은 바깥 total과 이름만 같은 다른 변수이고, 부를 때마다 0에서 시작한다 total = 0 for p in prices: total += p return totallines = sys.stdin.read().split("\n")n = int(lines[0])out = []for i in range(1, n + 1): nums = list(map(int, lines[i].split())) r = receipt_total(nums[1:]) out.append(r) total += rout.append(total)print("\n".join(map(str, out)))
JavaScriptmain.js · 21 行
// 하루 매출: 함수 밖(맨 위)에 둔 변수let total = 0;function receiptTotal(prices) { // let으로 새로 만들었으니 바깥 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 let total = 0; for (const p of prices) total += p; return total;}const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const out = [];for (let i = 1; i <= n; i++) { const nums = lines[i].trim().split(/\s+/).map(Number); const r = receiptTotal(nums.slice(1)); out.push(r); total += r;}out.push(total);console.log(out.join("\n"));
TypeScriptmain.ts · 23 行
import { readFileSync } from "node:fs";// 하루 매출: 함수 밖(맨 위)에 둔 변수let total = 0;function receiptTotal(prices: number[]): number { // let으로 새로 만들었으니 바깥 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 let total = 0; for (const p of prices) total += p; return total;}const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const out: number[] = [];for (let i = 1; i <= n; i++) { const nums: number[] = lines[i].trim().split(/\s+/).map(Number); const r: number = receiptTotal(nums.slice(1)); out.push(r); total += r;}out.push(total);console.log(out.join("\n"));
JavaMain.java · 29 行
import java.util.Scanner;public class Main { // 하루 매출: 메서드 밖에 둔 static 필드 static int total = 0; static int receiptTotal(int[] prices) { // 타입을 붙여 새로 선언했으니 필드 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 int total = 0; for (int p : prices) total += p; return total; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); StringBuilder out = new StringBuilder(); for (int i = 0; i < n; i++) { int k = sc.nextInt(); int[] prices = new int[k]; for (int j = 0; j < k; j++) prices[j] = sc.nextInt(); int r = receiptTotal(prices); out.append(r).append('\n'); total += r; } out.append(total).append('\n'); System.out.print(out); }}
C#Main.cs · 29 行
using System;using System.Linq;class Program{ // 하루 매출: 메서드 밖에 둔 static 필드 static int total = 0; static int ReceiptTotal(int[] prices) { // 타입을 붙여 새로 선언했으니 필드 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 int total = 0; foreach (int p in prices) total += p; return total; } static void Main() { int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { int[] nums = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); int r = ReceiptTotal(nums[1..]); Console.WriteLine(r); total += r; } Console.WriteLine(total); }}
C++main.cpp · 27 行
#include <iostream>#include <vector>// 하루 매출: 함수 밖에 둔 전역 변수int total = 0;int receiptTotal(const std::vector<int>& prices) { // 타입을 붙여 새로 선언했으니 전역 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 int total = 0; for (int p : prices) total += p; return total;}int main() { int n; std::cin >> n; for (int i = 0; i < n; i++) { int k; std::cin >> k; std::vector<int> prices(k); for (int& p : prices) std::cin >> p; int r = receiptTotal(prices); std::cout << r << '\n'; total += r; } std::cout << total << '\n';}
Cmain.c · 27 行
#include <stdio.h>// 하루 매출: 함수 밖에 둔 전역 변수int total = 0;int receipt_total(const int prices[], int k) { // 타입을 붙여 새로 선언했으니 전역 total을 가린 지역 변수다. 부를 때마다 0에서 시작한다 int total = 0; for (int j = 0; j < k; j++) total += prices[j]; return total;}int main(void) { int n; if (scanf("%d", &n) != 1) return 0; for (int i = 0; i < n; i++) { int k, prices[100]; if (scanf("%d", &k) != 1) return 0; for (int j = 0; j < k; j++) if (scanf("%d", &prices[j]) != 1) return 0; int r = receipt_total(prices, k); printf("%d\n", r); total += r; } printf("%d\n", total); return 0;}
Craykonmain.cray · 24 行
// 하루 매출: 맨 위에 둔 변수매출 = 0;// 크레이콘에서는 맨 위에 있는 이름에 함수 안에서 넣으면 그 바깥 변수가 바뀐다.// 그래서 영수증 합은 바깥에 없는 이름(합)으로 함수 안에서 만든다. 부를 때마다 0에서 시작한다영수증합(가격들){ 합 = 0; 遍历 (p 在 가격들) { 합 = 합 + p; } 返回 합;}n = 控制台.读行().转数字();循环 (i = 0; i < n; i++){ 수들 = 控制台.读数字(); r = 영수증합(수들.子列表(1, 수들.数量 - 1)); 控制台.输出(r); 매출 = 매출 + r;}控制台.输出(매출);