{ }codelper
return valuesdefining functionsP0402

A thermometer that cannot leave its scale

A classroom thermometer has marks only from lo degrees to hi degrees. If the real temperature is lower than lo the thermometer points at lo, and if it is higher than hi it points at hi. Otherwise it points at the real temperature itself. The first line gives lo and hi separated by one space. The second line gives n, the number of times the temperature was measured. Each of the next n lines gives one real temperature t. In the order measured, print the value the thermometer pointed at, one per line. On the last line print the sum of those n values. Write a function that receives the real temperature, lo and hi and returns the value the thermometer points at, and use the returned value for both the output and the sum. Grading looks only at the output.

Input
-100 ≤ lo ≤ hi ≤ 100, 1 ≤ n ≤ 100, -1,000 ≤ t ≤ 1,000 (all integers)
Output
n + 1 lines.
The first n lines are the values the thermometer pointed at, and the last line is their sum
Example 1 · stdin
-5 30
4
12
-9
30
41
stdout
12
-5
30
30
67
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

The frame for defining a function differs by language.
Python writes def shown(t, lo, hi): and JS writes function shown(t, lo, hi), with no types.
TS writes function shown(t: number, lo: number, hi: number): number, with the type of the returned value after the parentheses.
Java and C# write static int shown(int t, int lo, int hi) (usually Shown in C#), and C and C++ write int shown(int t, int lo, int hi), with the return type before the name.
Craykon writes only the name and parentheses, shown(t, lo, hi) { … }, and gives the value back with return t;.
A function ends as soon as it reaches return, so no else is needed below if (t < lo) return lo;.
Where the function may be placed also differs.
In Python the def must have run before the line that calls it; placed below, the program stops with NameError.
C++ gives a compile error when the function is not above the call, while C (gcc 11) only warns and compiles.
A JS/TS function declaration, a Java or C# method and a Craykon function may all sit below the call.
Trap one: leaving out the last return t; for a temperature inside the scale.
A Python function that ends without return returns None, so on the example it prints None on the first line and stops with TypeError on the line that adds to the sum.
JS returns undefined, and joining with join as the solution does turns undefined into an empty string, so the output for the example is an empty line, -5, an empty line, 30, NaN.
Java refuses to compile with "missing return statement" and C# with CS0161, and TS also stops it with TS2366 if you wrote : number.
C and C++ only get a warning from the judge's gcc 11 (-Wall) and still compile, and what happens afterwards is undefined.
Trap two: printing the value inside the function instead of returning it.
A value written to the screen does not come back to the caller.
In Craykon, writing Console.WriteLine(t) in place of return prints only the line 12 on the example and then stops on the line that adds to the sum, saying it cannot calculate with null.
Trap three: calling shown(t, lo, hi); and not taking the returned value.
In all eight languages an integer is passed as a copy, so changing t inside the function leaves the caller's t as it was.
Written this way, C compiles without a warning and the output for the example is 12, -9, 30, 41, 74.
Keep the returned value under a name, as in v = shown(t, lo, hi), so that you can use it twice: for the output and for the sum.

Pythonmain.py · 17 lines
def shown(t, lo, hi):    # 온도계가 가리키는 값을 돌려준다. return을 만나면 함수는 바로 끝난다    if t < lo:        return lo    if t > hi:        return hi    return t  lo, hi = map(int, input().split())n = int(input())total = 0for _ in range(n):    v = shown(int(input()), lo, hi)  # 돌려받은 값을 이름에 담아 두 번 쓴다    print(v)    total += vprint(total)
JavaScriptmain.js · 19 lines
// 온도계가 가리키는 값을 돌려준다. return을 만나면 함수는 바로 끝난다function shown(t, lo, hi) {  if (t < lo) return lo;  if (t > hi) return hi;  return t;} const lines = require("fs").readFileSync(0, "utf8").split("\n");const [lo, hi] = lines[0].trim().split(/\s+/).map(Number);const n = Number(lines[1]);const out = [];let total = 0;for (let i = 0; i < n; i++) {  const v = shown(Number(lines[2 + i]), lo, hi); // 돌려받은 값을 이름에 담아 두 번 쓴다  out.push(v);  total += v;}out.push(total);console.log(out.join("\n"));
TypeScriptmain.ts · 21 lines
import { readFileSync } from "node:fs"; // 온도계가 가리키는 값을 돌려준다. 괄호 뒤의 `: number`가 돌려주는 값의 타입이다function shown(t: number, lo: number, hi: number): number {  if (t < lo) return lo;  if (t > hi) return hi;  return t;} const lines: string[] = readFileSync(0, "utf8").split("\n");const [lo, hi]: number[] = lines[0].trim().split(/\s+/).map(Number);const n: number = Number(lines[1]);const out: number[] = [];let total = 0;for (let i = 0; i < n; i++) {  const v: number = shown(Number(lines[2 + i]), lo, hi); // 돌려받은 값을 이름에 담아 두 번 쓴다  out.push(v);  total += v;}out.push(total);console.log(out.join("\n"));
JavaMain.java · 25 lines
import java.util.Scanner; public class Main {    // 온도계가 가리키는 값을 돌려준다. 이름 앞의 int가 돌려주는 값의 타입이다    static int shown(int t, int lo, int hi) {        if (t < lo) return lo;        if (t > hi) return hi;        return t;    }     public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int lo = sc.nextInt(), hi = sc.nextInt();        int n = sc.nextInt();        int total = 0;        StringBuilder out = new StringBuilder();        for (int i = 0; i < n; i++) {            int v = shown(sc.nextInt(), lo, hi); // 돌려받은 값을 변수에 담아 두 번 쓴다            out.append(v).append('\n');            total += v;        }        out.append(total).append('\n');        System.out.print(out);    }}
C#Main.cs · 27 lines
using System; class Program{    // 온도계가 가리키는 값을 돌려준다. 이름 앞의 int가 돌려주는 값의 타입이다    static int Shown(int t, int lo, int hi)    {        if (t < lo) return lo;        if (t > hi) return hi;        return t;    }     static void Main()    {        string[] first = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);        int lo = int.Parse(first[0]), hi = int.Parse(first[1]);        int n = int.Parse(Console.ReadLine());        int total = 0;        for (int i = 0; i < n; i++)        {            int v = Shown(int.Parse(Console.ReadLine()), lo, hi); // 돌려받은 값을 변수에 담아 두 번 쓴다            Console.WriteLine(v);            total += v;        }        Console.WriteLine(total);    }}
C++main.cpp · 22 lines
#include <iostream> // 온도계가 가리키는 값을 돌려준다. 이름 앞의 int가 돌려주는 값의 타입이다int shown(int t, int lo, int hi) {    if (t < lo) return lo;    if (t > hi) return hi;    return t;} int main() {    int lo, hi, n;    std::cin >> lo >> hi >> n;    int total = 0;    for (int i = 0; i < n; i++) {        int t;        std::cin >> t;        int v = shown(t, lo, hi);  // 돌려받은 값을 변수에 담아 두 번 쓴다        std::cout << v << '\n';        total += v;    }    std::cout << total << '\n';}
Cmain.c · 23 lines
#include <stdio.h> // 온도계가 가리키는 값을 돌려준다. 이름 앞의 int가 돌려주는 값의 타입이다int shown(int t, int lo, int hi) {    if (t < lo) return lo;    if (t > hi) return hi;    return t;} int main(void) {    int lo, hi, n;    if (scanf("%d %d %d", &lo, &hi, &n) != 3) return 0;    int total = 0;    for (int i = 0; i < n; i++) {        int t;        if (scanf("%d", &t) != 1) return 0;        int v = shown(t, lo, hi);  // 돌려받은 값을 변수에 담아 두 번 쓴다        printf("%d\n", v);        total += v;    }    printf("%d\n", total);    return 0;}
Craykonmain.cray · 27 lines
// 온도계가 가리키는 값을 돌려준다. 돌려주기를 만나면 함수는 바로 끝난다가리킨값(t, lo, hi){    if (t < lo)    {        return lo;    }    if (t > hi)    {        return hi;    }    return t;} ends = Console.ReadNumbers();lo = ends[0];hi = ends[1];n = Console.ReadLine().ToNumber();total = 0;for (i = 0; i < n; i++){    // 돌려받은 값을 이름에 담아 두 번 쓴다    v = 가리킨값(Console.ReadLine().ToNumber(), lo, hi);    Console.WriteLine(v);    total = total + v;}Console.WriteLine(total);