Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

go - How scanf and scan parses the input

I had this simple problem statement which I tried implementing in Go.

Write a program to find the remainder when an integer A is divided by an integer B.

In the first piece of code i used fmt.Scanf and the test cases failed.

import "fmt"

func main(){
    var a,b,T int;
    fmt.Scanf("%d",&T);
    for i:=0; i<T; i++ {
        fmt.Scanf("%d",&a);
        fmt.Scanf("%d",&b);
        ans := a % b;
        fmt.Println(ans);
    }
}

The modulo operation was getting wrong answer. i got 0 2 0 instead of 1 100 10 on input

3 
1 2
100 200
40 15

but when I used fmt.Scan instead as in the following code cases passed, I was getting the right answer

package main

import "fmt"

func main(){
    var a,b,T int;
    fmt.Scan(&T);
    for i:=0; i<T; i++ {
        fmt.Scan(&a);
        fmt.Scan(&b);
        ans := a % b;
        fmt.Println(ans);
    }
}

Now my Question is why this happens. Does Scanf parses the input differently from Scan and which function to use for less error prone input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...