[英]How to get the first and last digit a user entered in C#
这是编程的新手,我需要一些有关此作业的帮助。 我们必须编写一个程序,要求用户输入以英寸为单位的数字,然后将其转换为码/英尺/剩余英寸,现在我把这部分记下来了。
但是,作业的最后一部分告诉我们显示用户输入的第一位和最后一位数字。 我不确定该怎么做。 我知道我可以通过取那个value % 10
来获得最后一位数字。
但是我不确定第一个值。 我的一些同龄人说使用.Length()
但他们也不确定,因为没有任何帮助。 有人可以帮我吗?
到目前为止,这是我的代码
Console.WriteLine("Gimme a number in inches");
int userInches = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("we will now calculate these inches into yards and feet and remaining inches.");
int inchesInFeet = 12;
int inchesInYards = 36;
int yards = userInches / inchesInYards;
int remainingInches = userInches % inchesInYards;
int feet = remainingInches / inchesInFeet;
int inches = remainingInches % inchesInFeet;
//display yards, feet and inches with respective lables
Console.WriteLine(userInches + " inches is: ");
Console.WriteLine(yards + " yards");
Console.WriteLine(feet + " feet");
Console.WriteLine(inches + " inches");
Console.ReadKey();
这里有些人对解决明显的家庭作业问题有些敏感。 一半的作业正在弄清楚。
无需付出太多,仍然可以回答:
尝试将其视为字符串。 您可以像这样访问一个字符串:
var s = "this is a string";
Console.Write(s[0]); // t
Console.Write(s[1]); // h
Console.Write(s[2]); // i
...
希望您应该能够从这里看到做什么。
这是一个家庭作业问题,您可以在其中展示自己的部分工作,我对此表示赞赏,即使某些社区可能并不认为这是一个很好的问题。
您注意到,任何number
的最后一位始终是number % 10
。 这是一个好的开始。
让我们以这种方式继续您已经了解的: int
方式(即使我更喜欢并推荐@Adam Schiavone在其他答案中给出的string
方式)
您应该知道:执行整数除法时 ,结果将被截断。 这意味着:
如果number
为int
,则number / 10
将除去最后一位数字。 因此,如果数字为2位数字,您将获得第一位数字!
int a = 45 / 10; // value of 'a' is 4 !
int b = 234 / 10; // value of 'b' is 23, not very interesting for you
如果number
是int
,则number / 100
将获得最后两位数字。 因此,如果数字为3位数字,您将获得第一位数字!
int c = 45 / 100; // value of 'c' is 0, not very interesting for you
int d = 234 / 100; // value of 'd' is 2 !
int e = 7893 / 100; // value of 'e' is 78, not very interesting for you
如果发现10
是像10到电源1, 100
是像10到电源2,且注意到图案制作号码长度和10的电力之间的链路来划分与号码,则可以理解的一般算法 ,以使用于获取您电话号码的第一位数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.