【发布时间】:2015-07-07 23:34:24
【问题描述】:
我有一个用户关于他们年龄的回复存储为int age;。然后我要求用户将他们的年龄除以某个数字,然后他们将该数字输入我的控制台。该号码存储为int rep;。从那里,我想问int rep; 是偶数还是奇数。我意识到您不能在 if () 语句中使用字符串。但是,我无法正确地提出我的问题以在网络上找到解决方案/帖子,这将帮助我了解如何检查我存储为字符串的用户输入是否可以与我期望的答案进行比较。
总而言之:对于字符串,if () 是否有等效的语法?
//Second task
int age;
int rep;
Console.WriteLine ("How old are you? ");
age = Convert.ToInt32 (Console.ReadLine ());
Console.WriteLine ("What is the your age divided by your first number submitted in the previous question? ");
rep = Convert.ToInt32 (Console.ReadLine ());
if (rep == age / num01 ) {
Console.WriteLine ("That is correct. Proceed to the next question. ");
} else
{
Console.WriteLine ("That is incorrect. Start over. ");
}
Console.WriteLine ();
//Third task
string ans;
Console.WriteLine ("Is your answer to the previous question an even or odd number? ");
ans = Console.ReadLine ();
if (rep % 2 == 0 && ans == even)
{
Console.WriteLine ("That is correct. ");
}
if (rep % 2 == 1 && ans == odd)
{
Console.WriteLine ("That is correct. ");
}
【问题讨论】:
-
为什么不能 if("string" == "string") ?
-
你也可以为奇数和偶数声明字符串局部变量。
-
@deathismyfriend 关于比较字符串的方法已经存在问题 - stackoverflow.com/questions/44288/…... 在大多数与用户输入相关的情况下,
==并不是最佳选择(正如您在您的答案)。这个问题的其余部分不太有趣——“如何使用if”几乎是题外话...... -
@AlexeiLevenkov 是的,还有其他问题,但我没有搜索它们。我也从未说过这是使用 == 的最佳方式。我将在下面的问题中添加更好的案例。
标签: c# string if-statement