部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

Offer--面试题集合

1. 设 m 和 n 都是 int 类型,那么以下 for 循环语句,c语言中循环体一次都不执行,Java中循环结束判断条件不合法

1
2
for(m=0,n=-1;n=0;m++,n++)
    n++;
  • 循环体一次也不执行
  • 循环体执行一次
  • 是无限循环
  • 有限次循环
  • 循环结束判断条件不合法
  • 运行出错

解释:c语言中  a=0返回值为0;a=1返回值为1;a=2返回值为2。

例:

int a ;
int i = (a=2);
cout<<i<<endl;

输出结果是2。 a=0或a=1时同理。

 

2. Which lines of the following will produce an error?

1
2
3
4
1byte a1 = 2, a2 = 4, a3;
2short s = 16;
3. a2 = s;
4. a3 = a1 * a2;

byte+byte=int,低级向高级是隐式类型转换,高级向低级必须强制类型转换,byte<char<short<int<long<float<double

所以3和4是错误的。

 

3. Given:

public class IfTest{
    public static void main(string[]args){
        int x=3;
        int y=1;
        if(x=y)
            System.out.println("Not equal");
        else
            System.out.println("Equal");
     }
}

What is the result?

  1. The output is “Equal”
  2. The output in “Not Equal”
  3. An error at line 5 causes compilation to fall.
  4. The program executes but does not print a message.

答案:3
解释:
其实这个是由于java和C语言的不同处理机制导致的: 

 

C语言中
当if语句中的条件为赋值语句时,实际上是将赋值后的结果与0进行比较【左值】
if(1)  由于1>0  所以认为是true 

 

java语言中,虽然也用了左值,但是不再与0比较,而是直接将0放入if()中。
但是int类型,不能转换为boolean,所以会报错:“ Type mismatch: cannot convert from int to boolean ”

 

posted @ 2015-05-19 21:31  流了个火  阅读(78)  评论(0)    收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats