問題1. 不能使用分号,編寫一個“Hello World”程式。
問題2. 如何用C語言列印“ I am print %”?
問題3. 不能使用">、<、>=、<=“等關系運算符,找到3個整數a ,b ,c中的最小的數。
問題4. 程式中不使用“+”法運算,實作整數加法運算。
參考程式:
1. 這是一個比較有趣的問題,但是答案往往十分簡單,所采用的是最基本的語句,參考程式如下:
#include <stdio.h>
void main()
{
if(printf("Hello World!\n")){} //可以換成while等
}
2. 對于初學者來說,有不少人不知道如何列印百分号這種類型的符号,其實也很簡單,無非是在前面加個百分号而已。
#include <stdio.h>
int main()
{
printf("I am print %%!");
}
3. 第3個問題有一定的挑戰性,而且答案不止一個,此外,關系運算符有:
參考程式:
#include <stdio.h>
#define min(a,b) (((a)-(b)) >> 31 ? (a) : (b))
int main()
{
int a , b , c;
a = -30;
b = 59;
c = 56;
printf("min = %d",min(min(a,b),c));
}
4. 不能使用"+"法運算,自然想到當初學的計算機組成原理的二進制相加的知識,采用位運算來實作相加:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int x,y; //輸入的兩個數
int inBit = 0x0000;
int tailBit = 0x0001;
int result = 0,Rbit;
int XlastBit,YlastBit;
int inBitREP;
printf("please input two numbers :");
scanf("%d%d",&x,&y);
while(tailBit)
{
XlastBit = x&tailBit;
YlastBit = y&tailBit;
Rbit = XlastBit^YlastBit^inBit;
inBitREP = 0;
if( (XlastBit == tailBit && YlastBit == tailBit) || ( XlastBit == tailBit && inBit == tailBit) || (YlastBit == tailBit && inBit == tailBit)) //超過兩個1,則進位為1
{
inBitREP = tailBit<<1;
}
inBit = inBitREP;
result = result|Rbit;
tailBit = tailBit<<1;
}
printf("The result is %d\n",result);
system("pause");
return 0;
}
以上便是C語言的幾個有趣的問題,希望學習C語言的童鞋們會喜歡,以上代碼均在CodeBlocks上運作無誤。第一次發文章,求各位大神輕噴!小弟先謝過了!
注:本部落格與部落格園上的部落格為同一部落客: http://www.cnblogs.com/bestDavid/