TypeScript 算术运算符示例

2018-12-26 16:26 更新

TypeScript 算术运算符示例

假设变量a和b中的值分别为10和5。

运算符描述示例
+(加法)返回操作数的总和a + b = 15
-(减法)返回值的差a - b = 5
*(乘法)返回值的乘积a * b = 50
 /(除法)执行除法运算并返回商a / b = 2
%(取余)执行除法并返回余数a%b = 0
++(递增)将变量的值增加1a ++ = 11
--(递减)将变量的值减少1a-- = 9

示例

var num1:number = 10 
var num2:number = 2
var res:number = 0
 
res = num1 + num2 
console.log("Sum:        "+res); 

res = num1 - num2; 
console.log("Difference: "+res) 

res = num1*num2 
console.log("Product:    "+res) 

res = num1/num2 
console.log("Quotient:   "+res)
 
res = num1%num2 
console.log("Remainder:   "+res) 

num1++ 
console.log("Value of num1 after increment "+num1) 

num2-- 
console.log("Value of num2 after decrement "+num2)

在编译时,它将生成以下的JavaScript代码:

//Generated by typescript 1.8.10
var num1 = 10;
var num2 = 2;
var res = 0;

res = num1 + num2;
console.log("Sum:        " + res);

res = num1 - num2;
console.log("Difference: " + res);

res = num1 * num2;
console.log("Product:    " + res);

res = num1 / num2;
console.log("Quotient:   " + res);

res = num1 % num2;
console.log("Remainder:   " + res);

num1++;
console.log("Value of num1 after increment " + num1);

num2--;
console.log("Value of num2 after decrement " + num2);

上述程序的输出如下:

Sum: 12 
Difference: 8 
Product: 20 
Quotient : 5 
Remainder: 0 
Value of num1 after increment: 11 
Value of num2 after decrement: 1




以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号