关于基本语法和问题的问题优先级C# [英] Question about basic syntax & precedence C#

查看:76
本文介绍了关于基本语法和问题的问题优先级C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c的新手#我工作表中的一个问题是:



会打印什么?

控制台。 WriteLine(35%4 * 3 + 2.3 - 6/4 * 3 +2);



现在通常这是8.8但控制台说这是10.3。我试过用不同的优先级计算几种其他方法进行试验,但我从来没有得到10.3 - 我得到的最接近的结果是10.8。



可以任何人张贴一步一步说明控制台如何读取此行以及它如何达到10.3的结果?



我尝试过:



计算它在纸上同时改变我更高优先级的修补,没有达到与控制台相同的结果

hi i am new to c# one of the questions in my worksheet was this:

What will be printed?
Console.WriteLine(35 % 4 * 3 + 2.3 - 6/4 *3 +2);

Now normally this would be 8.8 but the console says it is 10.3. I've tried experimenting by calculating with a different precedence several other ways, but I never end up with 10.3 - the closest result i reached was 10.8.

can anyone post a step-by-step of how the console reads this line and how it reaches the result of 10.3?

What I have tried:

calculating it on paper while changing tinkering with what i put higher precedence on, didn't reach same result as console

推荐答案

Quote:

将要打印什么?

What will be printed?

Console.WriteLine(35 % 4 * 3 + 2.3 - 6/4 *3 +2);



相当简单,优先级先说乘法,除法和模数,然后加上离子和减法。


Rather simple, the precedence say multiplications, divisions and modulo first, then additions and subtractions.

35 % 4 * 3 + 2.3 - 6/4 * 3 + 2
// gives
((35 % 4) * 3) + 2.3 - ((6/4) * 3) + 2
(3 * 3) + 2.3 - (1 * 3) + 2
9 + 2.3 - 3 + 2
10.3



唯一的技巧是在C中,带整数的除法是一个带整数结果的整数除法。


The only trick is that in C, a division with integers is an integer division with an integer result.


你怎么会得到别的东西? :D



试试这个:



((35%4)* 3)+ 2.3 - ((6/4)* 3)+ 2



请记住 6 / 4 使用整数完成,因此它产生 1 而不是 1.5
How would you get anything else? :D

Try this:

( ( 35 % 4 ) * 3 ) + 2.3 - ( ( 6 / 4 ) * 3 ) + 2

Bear in mind that 6 / 4 is done using integers, so it yields 1 rather than 1.5 .


你可以调整公式范围以强制按某种顺序发生事情,但你的例子中数学运算的顺序是:



0)root和exponents

1)乘法和除法

2)加法和减法



范围(使用括号对表达式的部分进行分组)可以覆盖括号外的正常优先级。
You could scope the formula to force things to happen in a certain order, but the order of math operations in your example would be:

0) roots and exponents
1) multiplication and division
2) addition and subtraction

Scoping (using parenthesis to group parts of the expression), can override the normal precedence that exists outside the parenthesis.


这篇关于关于基本语法和问题的问题优先级C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆