使用以下代码示例,为什么第一次添加(1/2 + 1/2)打印0,但第二次添加打印00.
System.out.println(1/2+1/2+"=1/2+1/2");
System.out.println("1/2+1/2="+1/2+1/2);
输出:
0 = 1/2 + 1/2
1 / + 1/2 = 00
答案 0 :(得分:4)
整数数学(int 1除以int 2是int 0,如果你想将一个或两个浮点结果转换为浮点类型的1和2)和操作顺序,第二个例子是{{ 1}}连接。编译器将其转换为
String
然后你得到
System.out.println(new StringBuilder("1/2+1/2=").append(1/2).append(1/2));
答案 1 :(得分:0)
第一个陈述" System.out.println(1/2 + 1/2 +" = 1/2 + 1/2");"打印0,因为从1/2获得的整数值为零。剩余部分被丢弃,因为1/2等于0.5,所以.5被丢弃。 第二个陈述" System.out.println(" 1/2 + 1/2 =" + 1/2 + 1/2);"由于串联符号,打印出00。在第二个语句中,第一个整数1显示为+1,因此该语句实际上被读取为(+1/2 +1/2),这就是它返回00的原因。 如果第二个语句设置如下:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$connection = mysqli_connect("localhost", "widget_cms", "password", "widget_corp");
// Make sure you chose the right database and table
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<html>
<body>
<form name="login" action="" method="post">
Username: <input type="text" name="username"></br>
<input name="submit" type="submit" value="Submit" style="cursor:pointer">
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['username']) ){
$username = $_POST['username'];
$username = mysqli_real_escape_string($connection, $username);
}
else {
echo "Name is empty.";
}
$query = "INSERT INTO subjects (menu_name) VALUES ('{$username}')";
$qresult = mysqli_query($connection, $query) or die(mysqli_error($connection));
if($qresult){
header("Location: second_page.php");
exit;
// Replace the header with echo "Success"; but don't use both header and echo
}else{
die("Error " . mysqli_error($connection));
}
}
?>
</body>
</html>
<?php
mysqli_close($connection);
?>
输出与第一个语句相同。
答案 2 :(得分:0)
从左到右评估表达。在第一种情况下,它会int+int
(0
),然后是int + "= String"
String tmp = "0= String"
。在另一种情况下,你有'“String =”+ int which becomes
“String = int”to which you append one more
int`。因此,您打印字符串,“0”和“0”。
答案 3 :(得分:-2)
java假定除法的结果是整数,因为它的成员是整数。对于每个除法的浮动结果(0.5),除数或被除数应为float
类型的System.out.println( “1/2 + 1/2 =” +(1 / 2.0 + 1 / 2.0));