[英]How to print variable's new value after it has been changed
If I have a program where x = 2 and I subtracted x by 1, making x = 1. Is there any way to make it so that whenever x will be printed in the program, it will print 1?如果我有一个程序,其中 x = 2 并且我将 x 减去 1,使 x = 1。有没有办法让它在程序中打印 x 时,它会打印 1?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x-1);
Console.WriteLine(x); //make x's new value 1
}
}
}
you need to store the calculation to the variable您需要将计算存储到变量中
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(x);//will print 2
x = x-1; //applying calculation and storing to same variable
Console.WriteLine(x); //make x's new value 1 : Done
}
}
}
Write写
x--;
Console.WriteLine(x);
That's how you change the value of a variable - you have to assign it a new value.这就是您更改变量值的方式 - 您必须为其分配一个新值。
Alternatively you can write x = x - 1;
或者你可以写
x = x - 1;
longhand instead of using the decrement ( --
) operator.手写而不是使用递减 (
--
) 运算符。
What you did in your version was to create some output which was the result of x-1, but that doesn't change the original value of x, it just uses x in another calculation.您在您的版本中所做的是创建一些 output 这是 x-1 的结果,但这不会改变 x 的原始值,它只是在另一个计算中使用 x。
You are Displaying the Correct answer.您正在显示正确答案。 2 - 1 will Display 1. But u arent changing the Variable or even touching it.
2 - 1 将显示 1。但你没有改变变量甚至触摸它。 You are just using it for a Reference to Calculate what is x - 1?
您只是将它用作计算 x - 1 的参考值吗? Displaying only X now will Display 2 as it has NOT been changed.
现在只显示 X 将显示 2,因为它没有被更改。
Setting (Changing the Value of a Variable) is not (normaly) possible inside a Function.在 Function 内部(通常)无法设置(更改变量的值)。 There are Functions which take ref params.
有些函数采用 ref 参数。 Which will work with its memory.
它将与它的 memory 一起使用。
You simply need a one-liner.你只需要一个单线。 x = x - 1 translated the value of x is set to the value of x - 1.
x = x - 1翻译后 x 的值设置为 x - 1 的值。
it seems much for a simple calculation to require a whole line as it is.一个简单的计算似乎需要一整行。 But programming will always be one of these things where u have to think literall
但是编程永远是你必须从字面上思考的事情之一
This whole problem is a great example for Rubberducking .这整个问题是Rubberducking的一个很好的例子。 think about it literall... line for line what exactly happens and why should it not work?
考虑一下字面意思...逐行究竟发生了什么,为什么它不起作用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.