简体   繁体   English

关于int的简单问题

[英]Simple question about int

Ok.... This seems like a simple question but I can't find any info about it so I thought I would ask here. 好的....这似乎是一个简单的问题,但我找不到有关它的任何信息,所以我想在这里问。

I am trying to store a number (int) in a var but I need to keep the 0's before it 我正在尝试在var中存储数字(int),但我需要在它之前保留0

eg: 例如:

int x = 0001;
NSLog(@"%i",x)  // returns 1

Is it possible to make it return 0001? 是否可以使其返回0001?

I know that i can do this: 我知道我可以这样做:

NSLog(@"%04i",x);  // returns 0001

But that is not quite the answer i am looking for because the number of 0's needs to vary. 但这并不是我要找的答案,因为0的数量需要变化。

I don't specifically need to use an int but it would need to be a whole number. 我不需要特别使用int,但它需要是整数。

The leading 0's are insignificant, and adding them will make the number an octal literal , so you can not log them with out specifying the width. 前导0无关紧要,将它们相加会使数字成为八进制文字 ,因此您不能在未指定宽度的情况下记录它们。 You can however specify a dynamic width to print. 但是,您可以指定要打印的动态宽度。

int dyn_width = 4;
int x = 1;

NSLog(@"%0*i", dyn_width, x);

If you need the string, rather than the value, you need to use a string variable. 如果需要字符串而不是值,则需要使用字符串变量。

NSString *x = @"0001";
NSLog(@"%@",x);

Then when you need to do some calculations, use "[x intValue]". 然后,当您需要进行一些计算时,请使用“ [x intValue]”。

Beside using a string, which you don't want, the only way I can see to code the number of 0s before the first significant digit is to store the value in a double , as 0.0001 . 除了使用不需要的字符串外,我看到的在第一个有效数字之前编码0的数量的唯一方法是将值存储为double ,即0.0001 Of course in some cases, precision might be an issue, not mentioning that arithmetic on that style of integer representations becomes more difficult. 当然,在某些情况下,精度可能是个问题,更不用说对这种整数表示形式进行算术变得更加困难了。

I would argue that the number of zeroes you're trying to display is not part of your model (the actual backing store, the int ), but of the presentation (so a function taking your int and displaying it somehow). 我认为您要显示的零个数不是模型的一部分(实际的后备存储, int ),而是表示的一部分(因此是一个将int并以某种方式显示出来的函数)。

Regardless, elementary math teaches us that 1 is the same number as 01 , so you'll have a hard time convincing the computer any differently. 无论如何,初等数学会告诉我们101是相同的数字,因此很难说服计算机。

You've got two options - create an object that both holds the int-value (1) the padding-count (3) and the padding type (zeros), or use a string. 您有两个选择-创建一个同时包含int值(1),padding-count(3)和padding类型(零)的对象,或使用字符串。 Using a string can cause other problems later (validation, can you stop other parts of the code putting string data like text in there?) 使用字符串以后可能会引起其他问题(验证,您是否可以停止代码的其他部分在其中放置文本之类的字符串数据?)

But, the real question is, why do you want this.. surely there's another way? 但是,真正的问题是,您为什么要这样做..当然还有另一种方法? Code refactor time! 代码重构时间!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM