取模和取余的符号:各语言写法汇总,收藏备用


1. C/C++:在C/C++中,取模操作使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

c

include

int main() {

int a = 10;

int b = 3;

int remainder = a % b;

printf("The remainder is %d", remainder); // 输出:The remainder is 1

return 0;

}

2. Java:在Java中,取模操作同样使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

java

public class Main {

public static void main(String[] args) {

int a = 10;

int b = 3;

int remainder = a % b;

System.out.println("The remainder is " + remainder); // 输出:The remainder is 1

}

}

3. Python:在Python中,取模操作使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

python

a = 10

b = 3

remainder = a % b

print("The remainder is", remainder) 输出:The remainder is 1

4. JavaScript:在JavaScript中,取模操作同样使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

javascript

let a = 10;

let b = 3;

let remainder = a % b;

console.log("The remainder is", remainder); // 输出:The remainder is 1

5. JavaScript (ES2020 引入的取模运算符):从ES2020开始,JavaScript引入了一个新的取模运算符 `%%`,它会向0取整,而 `%` 运算符会向负无穷取整。例如,`9 %% 3` 的结果是 `0`,而 `9 % 3` 的结果是 `0`。

javascript

let a = 9;

let b = 3;

let remainder = a %% b;

console.log("The remainder is", remainder); // 输出:The remainder is 0

6. Go:在Go语言中,取模操作使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

go

package main

import "fmt"

func main() {

a := 10

b := 3

remainder := a % b

fmt.Printf("The remainder is %d", remainder) // 输出:The remainder is 1

}

7. Ruby:在Ruby中,取模操作使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

ruby

a = 10

b = 3

remainder = a % b

puts "The remainder is {remainder}" 输出:The remainder is 1

8. Rust:在Rust中,取模操作使用 `%` 符号。例如,`a % b` 表示a除以b的余数。

rust

fn main() {

let a = 10;

let b = 3;

let remainder = a % b;

println!("The remainder is {}", remainder); // 输出:The remainder is 1

}

需要注意的是,虽然大多数语言都使用 `%` 符号来表示取模或取余操作,但具体行为(例如,对负数的处理方式)可能会因语言而异。在使用时,最好查阅相应语言的官方文档或相关资料,以确保正确理解和使用。