商科技藝競賽-程式
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 程式輸入輸出範例 tags: code, vb.net, python, ruby, java --- :::info Windows 環境請使用 CMD 作為終端機執行程式碼與編譯。 ::: # StdIn 範例 ## 範例輸入資料 ```= 22 1 23 1 24 1 ``` ## 範例輸出資料 ```= 23 24 25 ``` --- ## 範例程式碼 ### Python 程式碼 :::danger Windows 上 Python會有些功能無法與其他OS產生相同結果 請勿使用字串檔案路徑,請使用例如`os`等內建函式庫 ::: `main.py` ```python= import sys for line in sys.stdin.read().splitlines(): # splitlines 會去除不同OS的換行符號 nums = [int(num) for num in line.split()] # nums = map(int, line.split()) print(sum(nums)) ``` `$ python main.py < in.txt` ### Java 程式碼 `Main.java` ```java= import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String input = scanner.nextLine().strip(); String[] nums = input.split(" "); Integer result = 0; for(String s: nums) { result += Integer.parseInt(s); } System.out.println(result); } scanner.close(); } } ``` `$ javac Main.java` `$ java Main < in.txt` ### C 程式碼 `main.c` ```c= #include<stdio.h> int main(){ int a, b; while(!feof(stdin) && scanf("%d %d", &a, &b)){ printf("%d\n", a+b); } } ``` `$ gcc main.c -o main` `$ ./main < in.txt` ### C++ 程式碼 `main.cpp` ```cpp= #include<iostream> using namespace std; int main(){ int a, b; while(cin >> a >> b){ cout << a + b << endl; } } ``` `$ g++ main.cpp -o main` `$ ./main < in.txt` ### PHP 程式碼 `main.php` ```php= <?php $handle = fopen('php://stdin', 'r'); while($line = fgets($handle)){ [$a, $b] = explode(' ', $line); echo intval($a) + intval($b); echo PHP_EOL; } ``` ```php= <?php $data = explode(PHP_EOL, trim(stream_get_contents(STDIN))); foreach ($data as $item) { [$a, $b] = explode(' ', $item); echo (intval($a) + intval($b)) . PHP_EOL; } ``` `$ php main.php < in.txt` ### Rust 程式碼 > main.rs ```rust= use std::io; use std::io::BufRead; fn main() { for line in io::stdin().lock().lines() { let input = line.unwrap(); let nums: Vec<&str> = input.trim().split(' ').collect(); let result: i32 = nums .into_iter() .map(|x| x.parse::<i32>().unwrap()) .sum(); println!("{}", result); } } ``` `$ cargo build` `$ cargo run < in.txt` ### Go 程式碼 ```go= package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { result := 0 numbers := strings.Fields(scanner.Text()) for _, num := range numbers { n, _ := strconv.Atoi(num) result += n } fmt.Println(result) } if scanner.Err() != nil { log.Fatalln("Scanner Fail.") } } ``` ### Javascript 程式碼 `main.js` ```javascript= process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', processLine => { processLine.toString('utf-8').split('\n') .map(x => x.trim()) .filter(x => !!x) .map(data => { console.log(data.split(' ').reduce((x, y) => +x + +y)) }) }) ``` `$ node main.js < in.txt` ### Typescript 程式碼 <!-- :::info - Deno 1.0 ::: ```typescript= const buf = new Uint8Array(1024); const n = await Deno.stdin.read(buf); if (n !== null) { const lines = new TextDecoder().decode(buf.subarray(0, n)); lines.split('\n') .map(x => x.trim()) .filter(x => !!x) .map(data => { console.log(data.split(' ').reduce((x, y) => +x + +y, 0)); }) } ``` `$ deno run main.ts < in.txt` --> :::info `$ npm install -g typescript` > tsc ::: `main.ts` ```typescript= declare const process: any; process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', processLine => { processLine.toString('utf-8').split('\n') .map(x => x.trim()) .filter(x => !!x) .map(data => { console.log(data.split(' ').map(i => +i).reduce((x, y) => x + y)) }); }); ``` `$ tsc main.ts --outFile maints.js` `$ node maints.js < in.txt` ### Kotlin 程式碼 ```kotlin= fun main() { generateSequence(::readLine) .map { it.split(" ").map(String::toInt).sum() } .forEach(::println) } ``` ### Swift 程式碼 ```swift= import Foundation while let line: String = readLine() { let result: Int = line.trimmingCharacters(in: .whitespacesAndNewlines) .split(separator: " ") .map{Int($0)!} .reduce(0, +) print(result) } ``` `$ swift main.swift < in.txt` ### VB .Net 程式碼 :::info - VB .Net 2010 (Mono VB for Linux) ::: :::danger Mono VB 函式庫需要額外Import 即VB寫法會與visual studio有些差異 > 例如:ArrayList > 必須用 Imports System.Collections ::: `main.vb` ```= Module Module1 Sub Main() While True Dim Input As String = Console.ReadLine() If Input Is Nothing Then Exit While Dim Data() As Integer = Input.Split(" ").Select(Function(x) CInt(x)).ToArray Dim A As Integer = Data(0) Dim B As Integer = Data(1) Dim Output As Integer = A + B Console.WriteLine(Output) End While End Sub End Module ``` `$ vbc main.vb` 編譯程式碼 `$ main < in.txt` for windows `$ mono main.exe < in.txt` for mono ```shell= $ vbc main.vb -out:main.exe $ mono main.exe < in.txt ``` ### C# 程式碼 :::info - Mono C# for Linux ::: `main.cs` ```csharp= using System; using System.Linq; public class Test { public static void Main() { string line = Console.ReadLine(); while(line != null){ int[] nums = line.Split(' ').Select(x => Int32.Parse(x)).ToArray(); Console.WriteLine(nums[0] + nums[1]); line = Console.ReadLine(); } } } ``` `$ csc main.cs` `$ ./main < in.txt` ```shell= $ mcs main.cs -out:main.exe $ mono main.exe < in.txt ``` ### Ruby 程式碼 :::info - Ruby 2.5 ::: :::danger Windows 上 Ruby會有些功能無法正常運作 ::: `main.rb` ```ruby= ARGF.each do |input| puts input.split.map(&:to_i).sum end ``` `$ ruby main.rb < in.txt`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully