为什么if语句不执行? [英] Why doesn't the if statement execute?

查看:398
本文介绍了为什么if语句不执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int n = 777;

            string x = n.ToString();

            Console.WriteLine(x[2]);

            if (x[2] == 7)

            {

                Console.WriteLine("no.7");

            }

//output-

//7







no.7未打印。有什么东西我做得不对吗?



我尝试了什么:



那么,我还能尝试什么?




"no. 7" is not getting printed. Is there something which I haven't quite done right?

What I have tried:

Well, what could I have tried anyways?

推荐答案

Becasue 7和'7'之间存在很大差异

第一个是数字,第二个是字符。

A 字符串由一系列字符组成,因此777为string是777:三个字符'7'紧随其后。

一个字符可以包含'7',但它也可以包含'H','E','L','L '或'O' - 所以试图将它与数值进行比较只有在右字符集中使用该字符的值时才有效。

因此x [2]是单个字符'7',它与数字7的值不同。

试试这个:

Becasue there is a big difference between 7 and '7'
The first is a number, the second is a character.
A string is made up of a sequence of characters, so 777 as a string is "777": three characters '7' following each other.
A character can contain '7', but it can also contain 'H', 'E', 'L', 'L', or 'O' - so trying to compare it to a numeric value only works if you use the value for the character in a right character set.
And so x[2] is a single character '7' which is not the same value as 7 the number.
Try this:
if (x[2] == '7')

它会起作用。


您应该学习尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到有一点它会停止你所期望的。

在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



使用调试器,停止执行 if 并检查变量,你会看到 x [2] 中的内容和你会明白 7 7不一样。



您应该尽快阅读语言文档。
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

With the debugger, stop execution at the if and inspect variables, you will see what in x[2] and you will understand that 7 is not the same as "7".

You should read language documentation as soon as possible.


这篇关于为什么if语句不执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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