[問題] 字串轉數字不須判別正負?

看板C_and_CPP作者 (Puma)時間10年前 (2014/05/09 12:31), 10年前編輯推噓5(506)
留言11則, 8人參與, 最新討論串1/1
今天學校 C 語言老師教到字串轉數字,我本來寫先判別正負號的程式, 可是我同學沒有判別正負結果結果也正確,真的很奇怪。以下是程式碼 #include <stdio.h> #include <stdlib.h> int atoi(char *s){ int n = 0;//, t = 0; //if(*s == '-'){t = 1;s++;} while(*s)n = 10*n + (*s++) - '0'; return n; //return (t ? n : -n); } void main(){ printf("%d\n", atoi("-123456789")); system("pause"); } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.118.196.226 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1399609882.A.898.html

05/09 13:25, , 1F
為什麼很奇怪, 你拿atoi查到的應該是convert string to
05/09 13:25, 1F

05/09 13:25, , 2F
integer而不是positive integer或unsigned integer
05/09 13:25, 2F

05/09 13:29, , 3F
你用到了 <stdlib.h> 裡面的 atoi 了
05/09 13:29, 3F

05/09 13:38, , 4F
int atoi (const char * s);
05/09 13:38, 4F
我發現自己寫的函數是錯的... 我們老師說要教純 C 卻用 VC++ 當 Compiler 我真的覺得很奇怪 ※ 編輯: putumaxally (140.118.234.160), 05/09/2014 16:04:10

05/09 16:51, , 5F
VC++ 本來就可以編譯 C 啊, IDE 的名字只是名字而已
05/09 16:51, 5F

05/09 18:31, , 6F
C++ 不是 C 的 superset 嗎...
05/09 18:31, 6F

05/09 20:44, , 7F
↑ 不是
05/09 20:44, 7F

05/09 22:02, , 8F
05/09 22:02, 8F
VC++ 可以寫 .c 檔嗎,用 .cpp 不小心寫了 C++ 的語法也不會知道 像是 for(int i = 0;i < n;i++) 這種的。 還有 s25g5d4 大大貼的 wiki 說某些 C 的語法在 C++ 不能用。 ※ 編輯: putumaxally (175.181.149.63), 05/09/2014 22:11:22

05/09 22:26, , 9F
vc可以去設定 改成單純編譯C的阿~
05/09 22:26, 9F

05/10 02:50, , 10F
你舉的那個例子在 C99 就可以用了喔
05/10 02:50, 10F

05/15 21:29, , 11F
放心在VC寫.c吧 標準很舊想寫新標準也沒辦法XD
05/15 21:29, 11F
文章代碼(AID): #1JR5eQYO (C_and_CPP)