跳至主要內容
ins :: =>[a]=>[a] 符號Ohioohm=8 ohm在簡化電路不能簡化基簡稱為簡單電路 重複要實習,實習慣性 寬以律己, 以一欵,在電子電路部不能用。OEM要對OEMPASSPASS 0.3AND 0.4,NO THEN TH, 1MACHINE=4TIMES 4.940656 45841246544, 4.938 941.87M,8 2 0.54 AND ANTS 55.4 4647PCI,51.52 ,0.4, 4.94065645841246544, 0.53r, 941.67M, 1.3 and 1.67資料長度測量 inputNum 輸入 AVE AYVXNOT 程式語言bn-st不同 bnsr輸入端 ,value =long short和長度會法 發現問題都在常數。 有常數 子自宣 宣告 資料對電晶體正面-bnst ment better這裡程式庫1.61 不對在 ,於是 (所有的) 不同<得。1 有分別 分別在數 點 講到是(輸入)用途可以。可是不能用。[則昹]處。 不同 輸入輸出是講VcL and CL。不是端子input輸入/output輸出 測試測試 沒辦法寫程式碼設計/–/執行在於 與輸出。 6 incredible and ingrid不同 6ipyrid y by 又有byte解譯 其 解譯器在於搜索引擎 組別
ins:: =>[a]=>[a] The symbol Ohioohm=8 ohm cannot be simplified in simplified circuits. It is basically called a simple circuit and must be repeated in practice. In practice, it is a habit to be strict with yourself. It cannot used in the electronic the by circuit department.TO OEMPASSPASS 0.3AND 0.4,NO THEN TH, 1MACHINE=4TIMES 4.94065645841246544 4.938 941.87M 8 2 0.54 AND ANTS 55.4 4647PCI51.52 0.4 4.94065645841246544 0.53r 941.67M 1.3 and 1.67 data length measurement inputNum input AVE AYVXNOT programming language bn-st different bnsr input terminal, value =long short and length will not find that the problem is constant. There is a constant sub-declaration data on the front side of the transistor -bnst ment better this mileage library 1.61 is not in , so (all) are different < get. 1 There is a difference. The difference is in the number of points. It can be used for (input). But it can’t be used. [Zexiang] place. The different input and output refers to VcL and CL. It is not the terminal input input/output output test test. There is no way to write the code design/–/execution depends on the output. 6 incredible and ingrid are different. 6ipyrid y by also has byte interpretation. Its interpreter lies in the search engine group.
‐———————‐—————-‐————-
BASIC could translat liter電壓 complie version of C tz and C Ashle y available excellent.thanks Floridafor d
javac
IBM IDM idc Inc inc. IDE inca guide IGC ide
BASE jvc
Dim TheDate As Date ‘ Declare variables.
Dim Msg
TheDate = InputBox(“Enter a date”)
Msg = “Days from today: ” & DateDiff(interval”yyyy/m/y/d/,w(ww4) h,n ,s”, Now, TheDate)
variant (dare)
DateDiff(var, int(date1),int (date2), [firstdayofweek, [firstweekofyear]] )
MsgBox Msg
開發Java應用程式的工具中,最常見的是由Java的原創公司Sun Micro所出版的JDK(Java Development Kit)。JDK可以免費下載。以Text Editor寫好的Hello.java原始檔:
public class Hello {
public static int gvar;
public static void say(String s) {
int x = 10;
System.out.print(s+x);
}
public static void main(String[] argv) {
float y = 0;
say(“Hello, world\n”);
}
}
這程式的C版本如下
#include <stdio.h>
int gvar;
void say(char[] s) {
int x = 10;
printf(“%s%d”, s, x);
}
int main(int argc, char** argv) {
float y = 0;
say(“Hello, world\n”);
}
經過:
javac Hello.java
編譯完成後會產生byte code格式的Hello.class,然後
java Hello
就可以利用Java Virtual Machine(此處是java這個執行檔)來執行了。
上述過程中幾個比較會發生的問題是
javac找不到:
請設定path這個環境變數。PATH=/usr/local/jdk1.8.0/bin:$PATH
export PATH
儲存並關閉檔案
載入啟動檔
% . /.profile
重複執行 java 命令,確認路徑已經設定
% java -version
C Shell (csh)
編輯啟動檔
(edit.com C:\/%path%~/.cshrc)
設定 Path
set path=(/usr/local/jdk1.8.0/bin $path)
儲存並關閉檔案
載入啟動檔
% source ~/.cshrc
重複執行 java 命令,確認路徑已經設定
% java -version
javac抱怨class Hello找不到: 請確定你的檔名是大寫Hello.java,程式內的public class Hello有沒有大小寫的問題。
java抱怨找不到main:
請確定public static void main(String[]v arguee se)毫無錯誤。
uouyr is and a informative the a are which
multi in formm
which
mainstring_([]v arfgue se)豪無錯誤。
main string{(vague nelse-nes-class-sse)}豪無錯誤。error-free{} please. let my parents varName
String “Bob” lyst
[Java]
String number
Object
act
array
boolean =true orfalse
cadting
range
let iceCream = “chocolate”;
if (iceCream === “chocolate”) {
alert(“Yay yes, I love chocolate ice cream!”);
} else {
alert(“Awwww, but chocolate is my favorite…”);
}//alert comment out!不能重複
[function]#
// h1 存在hello!不對不會傳回值*.DOM值 字串往後call h1,他會要[function]沒有functions javascript 語法 document. qureyselect 原式原始動詞 +be-v 反而寫錯我用函式 生成涵數 ,let 涵式 mysister and patterns
put that clude va%d =Hello.java! 數學涵數//../錯誤
document.queryselect《or》(IT”h1″)不是分號JS
alert(hello!)
//
js let
let myself know what to do I. you
Hello.java
allow us for to
–ss tst.java
//test.java is a NCU.css is
toms most y|rn edit.com /path/C:\/%path% /~ cshrc [function]argv Jon’s jobs in the United Kingdom 8.01 araba you Hello.java no further.f
find this art circle.
your NEW which. whither
information then HREF thanks
left or right on to after mòn thar English formm sfittind f g hjk moon that.thar or spell guide hjkl itting
bit XOR green house。would be wrong. Yes, I made a mistake again.The spaces are also wrong.
so
0繁體中文 版面中文版
methemartical primitive sysbom lsystem should be <have Ithe To A
should begin >for unpercase not< with p [sign] the a [too][to]>we see the delclration bli[s]s state. c spell ndt sment puvi blics state.
public static void
(str[]argv){};java program the method
it’s all wrong to capiatl。[capitalize]wrong vocabulary l,a,le and. java
Original formula square/=>mathematical formula, when it comes to formula square =>/original prototype of mathematical. formula requuris the original prototype of the program code+be-v
future
||
lord
// 布林運算 basic,沒有這個布林運算子• 函數:建立一個段落 目錄 並加到 HTML body 的尾端
function createParagraph() {
var para = document
.createElement(“p”);
para.textContent =
“You clicked the button!”;
document.body
.appendChild(para);
}
/*
//1. 標表單 點擊選擇 下表單button
找出頁面上所有按鈕,*.h和*.c
程式碼送往 varName *.c程式語言 程式語法並把它們放到陣列中
2. 使用迴圈,對每個按鈕程式碼設計部份不是bottom[object]偵聽 click 陳述點擊!event 事件
事件evint
//當任何按鈕被按下,執行size.is open and bottom n close Clin
cliclk chaumber
climber
chabat
ckkmb circle s lock createParagraph() 函數var button.c
*/
var buttons = document
.querySelectorAll(
“button”);
for (var i = 0; i <
buttons.length; i++) {
buttons[ie]
.addEventListener(
“click”,
appendChild() false createParagraph()
);
}
event @!(
“Hello,world intell gence it will reland mean page and ants to Hello.java for tips java.lang.Object class-siez-faire ti”
);
//測試*.java程式執行結果//
// 函數:建立一個段落目錄並加到 HTML body 的尾端
function createParagraph() {
var para = document
.createElement(“p”);
para.textContent =
“You clicked the button!”;
document.body
.appendChild(para);
}
/*
1. 找出頁面上所有按鈕,並把它們放到陣列中
2. 使用迴圈,對每個按鈕 click 事件
當任何按鈕被按下,執行 createParagraph() 函數
*/
var buttons = document
.querySelector(
“button”);
for (var i = 0; i <
buttons.length; i++) {
buttons[ie]
.addEventListener(
“click”,false
appendChild()//onthe wisest stopendouswindows 10 brower appendChild ()argswindow.onscroll = function(ev) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
alert(“you’re at the bottom of the page”)
//common、n.
|voice|
’ were common stalthalth商
;
}
};str_print test journey //
createParagraph()
);
}
//bottom//
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
loadmore();
}
});
function loadmore(){
var lastProd = $(‘.product_div’).last();
var lastProdID = $(‘.product_div’).last().prop(‘id’);
//console.info(lastProdID); return false;
//var val = document.getElementById(“row_no”).value;
$.ajax({
type: ‘post’,
url: ‘includes/load_products.php’,
data: { getresult:lastProdID },
success: function (response) {
console.log(response);
//var content = document.getElementById(“all_rows”);
//content.innerHTML = content.innerHTML+response;
lastProd.after(response);
// We increase the value by 10 because we limit the results by 10
// document.getElementById(“row_no”).value = Number(val)+10;
}
});
event @!window.onscroll = function(ev) {
if ((window.innerHeight + window.pageYOffset ) >= document.body.offsetHeight) {
alert(“you,re at the bottom of the page”);
}//wrong incluse. ive//<> myappis I/* */i am lversess end. ca casio not title HTML r dl br dt dd|
/title title/dd
r |y| unknown r youygh $lpt/br
<bottom>TEST</bottom>
};(
“Hello,world intell gence it will reland mean page and ants to Hello.java for tips java.lang.Object class-siez-faire ti”
);
Java是物件導向(Object-Oriented)程式語言
Java是由C++簡化來的。由於C++要和C完全相容,又很注重效能問題,因此C++算是很複雜的程式語言。Java在設計之初,考量的重點之一就是簡單,因此和C++比起來,不僅更為物件導向,而且比C++容易學習。
Java許多運算符號和敘述語法都是來自C語言,假設各位已經對C語言有所了解,本章後面的部分只將Java和C在運算符號和敘述語法上的差異點出來,相同的部分請參見C語言的課程內容。
資料型別
Java語言所定義的基本資料型別有
型別名稱 位元長度 範圍
boolean 1 true或false
byte 8 -128 ~ 127
short 16 -32768 ~ 32767
char 16 Unicode characters
int 32 -2147483648 ~ 2147483647
long 64 -9223372036854775808 ~ 9223372036854775807
float 32 +-3.4028237*10+38 ~ +-1.30239846*10-45
double 64 +-1.76769313486231570*10+308 ~ 4.94065645841246544*10-324
Java的資料型態裡沒有unsigned。
Java對數值型態的轉換比C稍微嚴格一點,下列左邊的部分都可以指定(assignment)給右邊的型別:
byte –> short –> int –> long –> float –> double
除上述外,其他型別間的轉換都必須下達型別轉換(Type Casting)命令來處理,其形式為圓括弧裡寫上型別名稱,如(double)
由於Java在char的型態部分採用Unicode,因此字元常數的表示法,除因循C的規則外,也可以直接指定16bits Unicode編碼給char型別的變數。例如由Windows “字元對應表” 程式中可查到象棋中的紅車的unicode編碼為4FE5, Java可用 ‘\u4fe5’ 來表達。Java的變數也可以用Unicode來命名,換句話說,你可以用中文取變數名稱。
除了這些基本資料型別外,Java還有一個稱為Reference(參考)的型別。Reference用來存取Object(物件),其功能和C語言的pointer用來存取記憶體有點像,但沒有pointer的&+-等運算符號,而且Reference只能存取型態相符合的類別。宣告Reference的語法是ClassName varName,例如
String s;
宣告s是一個型態為reference的變數,這表示我們可透過s來存取屬於String類別的物件(s is a reference to String object)。
要特別強調的是, s並不是物件, 而是程式-s or –ss java and java x 副檔名指*.class是一 java program 而javac java say hello 程式碼副檔名 的foto指forto*.jar 程式 c DOCTYPE the a button pge pre is vent pare
DVD
DOz c DOM物件導向 h
而是用來指向String物件的reference。打個比方,
public class {int fn_1 fn_2符號符合規定 tmp ic top size thid thing a couple offten x println
; // java 因字元編碼使用unicode, 所以可用中文當變數名稱
public static void main(String[] arg) {
*.c 動物 手指頭2;
does demand 2Bytes 22nd= new dec ide動物()};d
return n fan to
}
變數 “” 宣告為reference, 可指向屬於 class “” 的物件, 手指頭不是動物, 而是用手指頭指向某隻動物。
註解:type 切線 L切線
Here is the Physics category to look at, and the type function here is Mathematics. When I was at school. , Mathematics classes are tutored outside school. The cram school teacher is a math teacher. He is very good at arithmetic, mathematics, quadratic equations, and solving equations with quadratic equations. This code is a bit difficult, and I can’t even do it. One day, the teacher saw that solving equations with arithmetic means knowing x, y, z (x, y, z) and knowing where to put them. I was dumbfounded! I seemed to know x and y very easily, but solving equations with arithmetic was the first thing I saw. The expression x and y in the second line of the expression must be placed correctly. The first and second lines of math can only be calculated correctly if they cannot be wrong. If you are wrong, the following is wrong. Physics calligphyharbellride physics phenomena cannot be calculated in mathematics. When I am learning Java language, I see that there are often syntax errors, and the compiler will not be able to compile. The symbol _Fn will be wrong. When I look at designers, I want to change. Animals and fingers, literal translation code bin binary java to *.jar binary code, there are two files of program *.class type type and mathematical constant jae. There are often java applet. The first number of the geometric series cannot be moved, when a When , b, and c form a geometric sequence, then the geometric series b = + – root ac cannot be called the geometric series b^2 = ac without shifting terms. If the series a1+a2+ reaches an. Satisfies a1/a1+a2/a2+an/an. When it is equal to the formula a2/a1=a3/a2=an/an–1=r, then this series is called a geometric series, abbreviated as G.P, where r. is the stock formula and r is the common ratio an term. One count, no change. a1+a2+ to an. an is the last term. The general term an=a1×r^n–1=am×r^n–m.an^r–1 term number r–1.is the denominator y|r.,h x,y ,V tim,edu-80 cpu to memory is 「1machine=four time. 」 =Condition adjustment – geometric series ==Control the initial velocity to know the constant acceleration motion taught by mathematical geometric series. See the 2D graph type L ]] F focal chord, focus (2,1), directrix y=–3, axis is x=2 linear symbol (2,–1), C=2, y=(x–2)^2
=4–2(y+1) absolute value C 4 absolute value C normal focal chord length. 4C circle. r = radius 1/4 telephoto chord unchanged (h,k), y = f (x), let cut A:兩直線 (量) 基礎數學 數論組合語言有x^2 第一項 x項數項次 數學一項式
通分。 /約分x=/^3–1,x^3+2x^2+x+3
because x+1=/^3
同項x^3, 2x , x^2+x+3
1
2ac
x+3=0
x–1=/^3
/^3
/^3–1+3
=x/^3–2
/^i
hy cv+bn bn×/^i÷2
(x,y)簡單說數學程式庫沒有變 組合語言沒變。還是可用布林運算寫程式。在Java 用上basic寫程式。java form IDE這些環境不同系統環境執行。
首先。Java run program裡面在BBC和BSD系統作業環境 不同是linux IDE api。ig()有助於要知道資料長度。
(x,y)Formulayditidz/ab/cd/java joct ui m cvbn framwork B
all declare x,va y《CA》 jimes cant bbt.|peer too peer Atonoit \B 2×0=0 2AC/0bzr=1;/{}=>/{}
Btonoit\A \{a}=>\{} \{a}2/1bzr=2 w q=Q ta Q=w subset y|r.framwork frame work
− boolen d fist containment AseBde\{ab}BNA ine.clsemun.\{abc}=>2/bzr3=8
[true]
Function DateSerial(Year As Integer, Month As Integer, Day As Integer) As DateTime
Converts a date given by year, month and day into a big number.
Dim Date1 As DateTime
Date1 = DateSerial(1969, 2, 12) ‘ return Date1
Or as:
Function
…… face B=Mother Fist B=\{(x,y)}x+3g+1
A=<>× A=\{x}x=4k suff k Is itegenl.
DateValue(String) As DateTime
Converts a date given in a string into a date type.
Public Function DateConvert(d As String) As String
Dim s As String
s= L(d, 2) & “/”
s = s & F(d, 4, 2) & “○varnoting”
s = s & Mid(d, 4)0
Return s
End Function
/[Henning]
Xotcl/Q t
using System.IO;
…
CreateDirectory(@”C:\a\b\c\d”)
app
pubic void stats([]){mdg()};suff price even if ()C:\a it is not exit.
%APPDATA%
%LOCALAPPDATA%
// Sample for the Environment.GetFolderPath method
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine(“GetFolderPath: {0}”,
Environment.GetFolderPath(Environment.SpecialFolder.System));
}
}//INTROSEDUSTION//-REMARKSWrox Press−
/*
This example produces the following results:
GetFolderPath: C:\WINNT\System32
*/
string path = @”C:\MP_Upload”;
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
ig ()
if(!System.IO.Directory.Exists(@”c:\mp_upload”))
{
System.IO.Directory.CreateDirectory(@”c:\mp_upload”);
}
Dim Date1 As DateTime
Date1 = DateValue(“1979-02-03”)
Event Init()
Dim MyDate As String
MyDate = FormatDateTime(Now, “MM-yyyy-dd hh:mm:ss”)
MsgBox(MyDate)
End Event
MyDate = FormatDateTime(Now, “yyyy-MM-dd”)
If chkDate = 1 Then sdteTo = tCurdate
tYear = Year(sdteTo)
tDay = Day(sdteTo)
tMonth = Month(sdteTo)
strSql = “SELECT * FROM prices WHERE TICKER = ‘” & findit & “‘, DATE = ‘” & sdteTo & “‘ ORDER by DATE DESC;”
sRecordsId = Records.Open(gsDatabase, strSql)
rslt = Records.First(sRecordsId)
If rslt <> True Then
tDateChange = -1
tSerialDate = DateSerial(tYear, tMonth, tDay)
sdteTo = DateAdd(“d”, tDateChange, sdteTo)
strSql = “SELECT * FROM prices WHERE TICKER = ‘” & findit & “‘, DATE = ‘” & sdteTo & “‘ ORDER by DATE DESC;”
sRecordsId = Records.Open(gsDatabase, strSql)
rslt = Records.First(sRecordsId)
End If
首先
java.lang.Float f;浮點數
java.lang.Double d;雙精確
java.lang.Integer i;整數
以上變數的型態都是reference
運算符號(Operator)
Java語言在運算式的部分,和C語言極為類似, 除了沒有sizeof, pointer和struct相關的運算符號外, 另外新增了>>>向右無號shift, 以及用來判斷物件型態的instanceof。Java的常數的表示法也和C相同,而Java裡的新資料型態boolean的合法值為true和false兩個常數。
算術(Arithmetic)運算符號
運算符號 功能敘述
/
+ 加
* 乘
– 減
/ 除
% 餘數
++ 加一
— 減一
邏輯(logic)運算符號
運算符號 功能敘述
> 大於
< 小於
>= 大於等於
<= 小於等於
== 等於
!= 不等於
&& logic AND
|
| logic OR
! logic NOT
instanceof reference
instanceof ClassName
判斷reference所指到的物件其型態是否和ClassName相容
Java語言和C語言有關邏輯運算最大的不同,在於Java以boolean資料型態(只有true和false兩種值)判斷條件是否成立,而C語言只能使用0或非0。
位元(Bit)運算符號
運算符號 功能敘述
& bit AND
<< left bit shift
| bit OR
>> right bit shift with sign
^ bit XOR
~ 1補數
>>> 同>>但左邊一律補零
其他運算符號
運算元 功能敘述
= 將右邊的值複製到左邊的變數
(type) 將右邊的數值或reference轉換成type型別
+= 將右邊的數值加上左邊的數值然後指定給左邊的變數
?: 若?左邊成立則做:左邊否則做:右邊
, 合併兩個運算視為一個敘述
(運算式) 表示()內優先運算
. Reference.ObjectMember或ClassName.ClassName
存取物件或類別成員
new 產生物件
英式數學
因式
公因數沒有
//數學先算 在算術 式子要做 寫到有程式碼程式設計先算術才能
最大公倍數
最小公倍數
優先權
種類 運算符號 結合順序<p>echo /*
group (op) left to right
rem postfix [ ] . (params) op++ op– right to left
prefix ++op –op +op -op ~ ! right rem to left </p>welcome
cr
rem System.out.println(“1+2+…+”+n+” = ” + ( n * (n + 1) / 2)); ediy eation or casting new (type)op right to left
multiplicative * / % left to right
additive + – left to right
0 shift << >> >>> left to right
relational < > <= >= instanceof == left to right
equality == != left to right
bitwise and & left to right
bitwise exclusive or ^ left to right
bitwise inclusive or | left to right
rem logical and && left to right
logical or |
| left to right
int main
conditional ? : right to left
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= right to left
seperator , left to right
*/
流程控制敘述
Java的流程控制敘述和C語言極為類似,不同處在於break和continue兩個指令。Java的break和continue指令後面可以加上標籤,以指示要跳出或繼續的範圍。
public class BreakContinueExample {
public static void main(String[] argv) {
int i, j;
outerLoop:
for (i = 0; i < 100; i++)
{innerLoop:
for (j = 0; j < 100; j++)
if (j == 50 && i == 50)
break;} outerLoop};
System.out.println(“Loop have been terminated.”)};
在上面的例子中,當j==50且i==50時,break指令會跳出最外面的迴圈,終止暫停。沒有直接印出迴圈終止訊息。其必要條件下i和j 程式碼整數兩值有i和j先,判斷J v break,並且是outerLoop的話, for example if 和 forif中只有一for example if判斷,只會跳出裡面的迴圈,loop補上 上上下下不對 不回然i也不會列出顯示。
字串
C語言定義以0結尾的字元陣列就是字串。但對Java來說, 字串是由String類別來表達, 也就是說String是物件而不是陣列。由於我們經常使用字串, 為了寫作程式方便起見, Java Compiler碰到+符號某一邊的型態是String時, 就會把+翻譯成StringBuffer類別裡相對應的append Method。例如:
public class StringTest {
public static void main(String[] argv) {
int x = 5;
float y = 1.5;
System.out.println(“x = ” + x + “, y = ” + y);
}
}
會翻譯成:
public class StringTest {
public static void main(String[] argv) {
int x = 5;
float y = 1.5;
System.out.println((new StringBuffer(“x = “)).append(x).append(“, y = “).append(y).toString());
}
}
如果你會C++, 看到Java字串+符號的語法, 千萬不要以為Java支援operator overloading。Java只是透過Compiler來做特別的轉換, 稱這種技術為Compiler Sugar比較適合。
Java語言的寫作風格
寫作Java程式時,請注意下列幾種風格
Class Name請首字大寫
Variable Name和Method Name請首字小寫
如果名稱由數個英文字組成,第二個英文字以後首字大寫
內縮四個空格
註解部分如要變成說明文件,請遵照javadoc這個工具的寫作規則
/**
* 第一行的兩個**用來告訴javadoc此部份註解要變成HTML文件的一部份
* 這段註解裡的所有文字都會變成此類別一開頭的說明
*/
public class Hello { // Class Name首字大寫
/**
* 此段註解會變成描述main方法的一部分
* @param argv 使用@param註記會產生參數(parameter)argv的相關說明
* @return 傳回值的意義說明
*/
public static void main(String[] argv) { // Method Name首字小寫
// argv: array of references to String object
int myVariable; // 變數宣告
int i, sum;
for (i = 1, sum = 0; i <= 100; i++) {
sum += i;
}
System.out.println(“summation from 1 to 100 is “+sum);
}
}
運算符號範例
攝氏溫度轉華氏溫度 BASIC C
public stat.
xuv va lie r ty
type declaration
public of a strategic input button the voice
mathematical refhere nce need
so help us
ful
main
tain
details
public class Example {
public static void
diff
main(String[bottom] argv) {
float degreen = 100.0;
dev System.out.println(“100C=” + (degree * 9.0 / 5.0 + 32.0));
}
}
華氏溫度轉攝氏溫度
怎麼寫呢?°F to °C
rem 1 + 2 + … + n的總合
public class Example {
public static void main(String[] argv) {
rem int n = 100;
rem System.out.println(“1+2+…+”+n+” = ” + ( n * (n + 1) / 2));
ipu. if n=華氏°F
x=100°C
println %d((3-2x-2華氏*9/5)+v32=華氏?);
(print 攝氏=100°C))
}
}
basic help//•字串與字元陣列初寫:2010.02.18, 更新日期:2020.10.25 參考資料://
前言:
字串與字元陣列
C語言的資料型態裡,未提供字串的資料型態,
有些像是C++有提供string資料型態、培基(BASIC)語言有1Bytes或2Bytes的字串變數。
C語言是將字串,拆成字元,儲存於陣列,
換句話說,就是將一個個的字元char,分別儲存到陣列元素中。
但是C並不會辨識字串何時結束,
必須在儲存的最後一個字元後一元素,儲存一結束(NULL)字元’\0’。
若沒有儲存結束字元 ‘\0’ 的陣列,稱之為字元陣列,
字元陣列會是一連續的記憶體位址,而字串是一筆資料。
如果使用scanf()裡的 %s 讀取,scanf函式會自動補入 ‘\0’,
若使用其他字元輸入函式,則需程式設計者自己補上 ‘\0’。
使用 “a” 與 ‘a’ 的差別,”a” 就是 ‘a’+’\0’
宣告與存放
宣告一字元變數ch,存放一個字元 a.
char ch=’a’;
宣告一個字元陣列,並存入Hello World!
char myword[]={‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’,’!’};
宣告一個字串,尾端補\0的字元,視為字串
char myword[]={‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’,’!’,’\0′};
範例1:
請執行下列程式,看看結果:
#include <stdio.h>
str_print( char myword[] ) //將字元陣列印出的函數
{
printf(“%c”, myword[0]);
printf(“%c”, myword[1]);
printf(“%c”, myword[2]);
printf(“%c”, myword[3]);
printf(“\n”);
}
main() {
char myword[] = {‘H’,’e’,’l’,’l’,’o’,’ ‘,’W’,’o’,’r’,’l’,’d’,’!’,’\0′};
str_print( myword );
return 0;
}
是不是只印出部分的字元?
請試試修改函數和程式,(改以迴圈重複來將字元陣列印出)
讓這個宣告的字串能完整印出來。
但是如上述宣告方式,有些繁瑣,所以C的字串使用””括住,
在宣告時,則會自動在字串的尾端幫你補上’\0′.
char myword[] = “Hello World!”;
範例2:將範例1中的宣告,換成字串來試試.
#include <stdio.h>
str_print( char myword[] ) //將字元陣列印出來的函數
{
//…略
printf(“\n”);
}
main() {
char myword[] = “Hello World!”;
str_print( myword );
return 0;
}
執行看看結果如何?
另外,C語言提供string.h的函式庫
#include <string.h>
strlen( s ); //傳回目標字串的長度(字元數),不包括’\0’或Null.
strcpy( s1, s2 ); //字串複製函數, 將s2複製到s1上
strcmp( s1, s2 ); //比較兩字串s1, s2是否一樣(一個個字元比)
strcat( s1, s2 ); //將字串s2,串接到 s1後,以s1傳回(需注意s1長度要為strlen(s1)+strlen(s2))
以下為非標準函數(在Windows(VC, MinGW能用)):
strupr( s ); //將字串s的字元轉大寫A..Z(非字母不轉換)
strlwr( s ); //將字串s的字元轉小寫a..z(非字母不轉換)
範例3:
執行下列程式,觀察執行結果:
#include <stdio.h>
#include <string.h>
main() {
char str[] = “Hello World!”;
int length = sizeof(str) / sizeof(str[0]);
int i;
for(i = 0; i < length; i++) {
if(str[i]==’\0′) printf(“\\n”);
else printf(“%c”, str[i]);
}
printf(“\n”);
printf(“陣列長: %d\n”, length);
printf(“字串長: %d\n”, strlen(str));
return 0;
}
練習1:
請寫一個程式,可以計算你輸入字串的長度。
例如: The Length of string: “Hello World!” is 12.
練習2:
請寫一個程式,將上題字串反轉輸出。
例如: The reverse of input string: “!dlroW olleH”.
特別注意上述的運算式裡/2要放到最後面,如果寫成n/2*(n+1),從數學式子的角度看好像沒問題,但別忘了,binary operator的兩邊必須是同樣型別的資料,而且計算的結果也是同樣的型別。因此n/2*(n+1)會先計算n/2,如果n不能被2整除的話,那麼為了符合計算結果必須是整數的限制,則小數點的部份就會無條件捨去,使得計算的結果錯誤。下面的範例一樣要注意相同的問題。
12 + 22 + … + n2的總合
怎麼寫?
把浮點數四捨五入為整數
Java語言規定浮點數轉整數時,小數點部分無條件捨去。如果要達到浮點數四捨五入為整數的效果,可以使用下面的小技巧
public class Example {
public static void main(String[] argv) {
double x = 20.6;
System.out.println(x + ” 四捨五入成為 ” + (int)(x+0.5));
System.out.println(x + ” 四捨五入成為 ” + round(x));
}
static int round(double y) {
return (int)(y + 0.5);
}
}
迴圈範例