由买买提看人间百态

topics

全部话题 - 话题: printf
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)
c*********t
发帖数: 2921
1
来自主题: JobHunting版 - 求顺时针打印矩阵code
那就两个loop就行了。
第一个loop 是row,
第二个loop是column
第二个loop退出的时候换行。
printMatrix(M[][], n)
{
for (int row=0; row {
for (int col=0; col printf("%d ", M[row][col]);
printf("\n");
}
}
l**********3
发帖数: 161
2
来自主题: JobHunting版 - 求顺时针打印矩阵code
贴个简单点的,但是比较长 。。。
==============
#include
#include
#include
#include
using namespace std;
enum direct_t { RIGHT, DOWN, LEFT, UP };
void print_spiral_matrix(int dimX, int dimY)
{
int** matrix = new int*[dimX];
for (int i=0; i {
matrix[i] = new int[dimY];
memset(matrix[i], 0, sizeof(int)*dimY);
}

int num = 1;
direct_t dir = RIGHT;
int i, j;

for (i=j=0; num <= dimX*dimY; ++num)
{
ma... 阅读全帖
b*******8
发帖数: 37364
3
来自主题: JobHunting版 - 求顺时针打印矩阵code
以前我写的,测试过:
#include
void main()
{
const int size=7;
int a[size][size];
int x,y,val=0;
for(x=0;x for(y=x;y for(y=x;y for(y=size-x-1;y>x;y--) a[size-x-1][y]=++val;
for(y=size-x-1;y>x;y--) a[y][x]=++val;
}
if (size%2) a[size/2][size/2]=++val;
for(x=0;x for(y=0;y printf("\n");
}
getchar();
}
c*********t
发帖数: 2921
4
来自主题: JobHunting版 - 问一道面世题
gate 说的是对的。
我写了个完整的:
void get_missing_via_swap(int a[], int n)
{
int i;
for (i = 0; i < n ; i++)
{
if(a[i] != a[a[i]-1])
{
swap(&a[i], &a[a[i]-1]);
i--;
}
}
for(i = 0; i < n; i++)
{
if(a[i] != i+1)
{
printf("the missing number is %d\n", i+1);
printf("the duplicated number is %d\n", a[i]);
break;
}
}
}
k***d
发帖数: 4
5
来自主题: JobHunting版 - 一家游戏公司的新鲜面经
#include
#define N 3
#define MAXN 10
void gen(int level){
int i, j;
static int dice[MAXN]; /* global array also works */

if(level <= N){
for(i = 1; i <= 6; i++){
dice[level] = i;
gen(level+1);
}
}else{
for(j = 1; j <= N; j++){
printf("%d", dice[j]);
}
printf("\n");
}
}
int main(){
gen(1);
return 0;
}
h****a
发帖数: 70
6
来自主题: JobHunting版 - 再问个fork的题 (转载)
【 以下文字转载自 Linux 讨论区 】
发信人: himdca (how are you doing?), 信区: Linux
标 题: 再问个fork的题
发信站: BBS 未名空间站 (Thu Jun 9 03:31:30 2011, 美东)
Given the following code:
#include
int main(void)
{
int tmp;
tmp = fork();
if(tmp == 0)
{
printf("Hello ")
sleep(1)
}
else if(tmp > 0)
{
printf("World, ")
sleep(1)
}
print "Bye bye"
}
Assuming the call to fork doesn't fail, which of the following is true (zero
o... 阅读全帖
s**x
发帖数: 405
7
来自主题: JobHunting版 - Ask a google interview question
void search(int n, int l){
int i;
for (i=31;!((n>>i)&1);i--);
for (;i>=0;i--) printf("%d",(n>>i)&1); printf("\n");
for (i=0;i>i)&7)==4) search(n^(7< }
void fib(int n){
if (n<=0) return;
int i,j,k,t[32]={1,2};
for (i=1;n>=t[i];i++) t[i+1]=t[i-1]+t[i];
for (j=0,k=i-1;n;k--) if (n>=t[k]) { n-=t[k];j|=(1< search(j,i);
}
s*******f
发帖数: 1114
8
来自主题: JobHunting版 - [算法]打印所有因子乘积组合
int GetNextPrime(){ // substitute this with more excellent algorithm
static int primes[] = {2,3,5,7,11};
static int idx = 0;
return primes[idx++];
}
void PrintFactors(int n){
if (n < 0){
n = -n;
}
if (n == 0){
return;
}
int prime = 1;
while (prime <= sqrt(double(n))){
prime = GetNextPrime();
while (n % prime == 0){
printf("%d ", prime);
n /= prime;
}
}
if (n > 1){
printf("%d ", n);... 阅读全帖
S**I
发帖数: 15689
9
来自主题: JobHunting版 - 问一道 C/C++ 题
try the following:
char *s1 = "firststring";
char *s2 = "secondstring";
char *t1 = ToUpper(s1);
char *t2 = ToUpper(s2);
printf("%s\n", t1);
printf("%s\n", t2);
f*******t
发帖数: 7549
10
来自主题: JobHunting版 - 问一道 C/C++ 题
使用静态buffer虽然不安全,但不能说就是错的,主要看运行的结果如何使用。像前面
那个程序如果先printf string1再处理并printf string2,就不会有问题。
如果返回的字符串不是立即使用,有两种办法:动态分配空间,和直接修改原字符串。
动态分配空间最大的坏处在于,使用完之后需要手动释放,一旦忘记就会造成内存泄露
。所以建议在调用ToUpper()前分配好空间,将指针传入函数由它修改。
另外用分配在栈上的空间作为buffer,返回一个指针,很可能等不到使用这段内存就被
释放了,程序出现内存错误。
还有就是楼主的代码没有检查数组越界的问题,如果传入的字符串长度超过了1000就会
出问题。
W**********r
发帖数: 8927
11
In memory of the ...
printf("Hello World\n");
printf("Bye bye ~~\n");
W**********r
发帖数: 8927
12
Yeah:
printf("Hello World\n");
printf("Bye bye ~~\n");
q**p
发帖数: 147
13
来自主题: JobHunting版 - 问两个题
1,
void newBuffer(char* outBuffer, size_t sz) {
outBuffer = new char[sz];
}
int main() {
const char* kung = "KUNG";
char* foo;
size_t len = strlen(kung);
newBuffer(foo, len);
memset(foo, 0, len+1);
strncpy(foo, kung, len);
cout << foo << endl;
}
这个可以编译,但是有bug,运行之后知道是foo的问题,具体不太明白,求指点
2,
B is a class inherited from A.
B *myPointer = new B();
A *myOtherPointer = myPointer;
printf(“%x”, myPointer);
printf(“%x”, myOtherPointer);
这段代码的两个... 阅读全帖
s*******f
发帖数: 1114
14
来自主题: JobHunting版 - msft校园面经 amazon三次电面面经
// 打印从棋盘的一个角落到另一个角落所有路径
// this is toooooo hard, seems NP hard. cannot be DP
// if chess can only go right or down, here it is
struct Point{
int x;
int y;
Point(int xx, int yy):x(xx),y(yy){ };
friend bool operator== (Point &p1, Point &p2);
};
bool operator== (Point &p1, Point &p2){
return p1.x == p2.x && p1.y == p2.y;
}
void PrintPoint(Point &p){
printf("(%d, %d)", p.x, p.y);
}
void PrintAllChessPath(Point &p1, Point &p2){
static vector path;
path.push_back... 阅读全帖
s*******f
发帖数: 1114
15
来自主题: JobHunting版 - msft校园面经 amazon三次电面面经
// 打印从棋盘的一个角落到另一个角落所有路径
// this is toooooo hard, seems NP hard. cannot be DP
// if chess can only go right or down, here it is
struct Point{
int x;
int y;
Point(int xx, int yy):x(xx),y(yy){ };
friend bool operator== (Point &p1, Point &p2);
};
bool operator== (Point &p1, Point &p2){
return p1.x == p2.x && p1.y == p2.y;
}
void PrintPoint(Point &p){
printf("(%d, %d)", p.x, p.y);
}
void PrintAllChessPath(Point &p1, Point &p2){
static vector path;
path.push_back... 阅读全帖
s*******f
发帖数: 1114
16
来自主题: JobHunting版 - 二维数组参数怎么传好?
u are goddamn right
template
void foo(int m[][width], int height){
for (int i = 0; i < height; ++i){
for (int j = 0; j < width; ++j)
printf("%d ", m[i][j]);
printf("\n");
}
return;
}
int main(){
int a[3][2] = {{1,2},{3,4},{5,6}};
foo<2>(a,3);
}
k***t
发帖数: 276
17
来自主题: JobHunting版 - Facebook电面题目
本人一直只写C,看过一点STL。欢迎大家 Code Review。谢谢。
觉得has_next_level flag 部分不够简单明了,但没有它不好
在输出中换行和终止加dummy node.
#include
using namespace std;
typedef struct TreeNode_ {
int value;
struct TreeNode_ *left;
struct TreeNode_ *right;
} TreeNode;
int level (TreeNode *root) {
queue Q;
TreeNode *cur, dummy;
bool has_next_level;

if (!root) return -1;
Q.push(root); Q.push(&dummy);
has_next_level = false;

while(!Q.empty()) {
cur = Q.front();
... 阅读全帖
g*********e
发帖数: 14401
18
来自主题: JobHunting版 - google这是什么意思?

我答的是这样的,请大家指正。
我谈了做实习时给图做优化,sign extension的问题。eda的东西,他听了似乎不是太
有兴趣。
hashtable O(1) access time, no order,通过key来map
bst O(logn) time, but can retain the order of stored item
我一开始说bst是balanced tree. 他指出不是。又问bst不balance会怎么样,worst
time analysis. 以及有啥方法balance. 我跟他说avl tree 或者红黑树,但没要求写
具体代码。
接着还追问了hash collision怎么处理,我说可以弄个list append上去,或者probing
(然后稍微解释了下probing)
我首先想到的是debug statement的副作用,可能里面执行了什么函数。其他我说想不
出来。他说加了一行code会改变什么?我说executable大小会改变,load到内存位置也
会不一样。我说可能是内存某一块坏了,刚好load到了那块。接着他问还会改变什么?
我说可能... 阅读全帖
z****u
发帖数: 104
19
字符串的 permutation 肯定是比较基础的题了,可是自己写了一下发现要 bug free
真心很难啊。调试了半天才 ok,而且程序看起来很臃肿,这要是在白板上铁定写不出
来啊
求大家指点一下该向哪个方向改进?
#include
#include
#include
char* insert(char* dst, int n, char c, int j)
{
/* Insert char c into string dst at location j */
n++;
dst = (char*) realloc(dst, sizeof(char) * n);
while(j < n)
{
char tmp = dst[j];
dst[j] = c;
c = tmp;
j++;
}
return dst;
}
char** permutation_recursive(char* s, int n, in... 阅读全帖
x********3
发帖数: 160
20
来自主题: JobHunting版 - 练练DP吧,呵呵
第二题我想是可以用greedy的。我基本的思路是首尾两项肯定是在选的elements中的。
初始化是选择的序列是0,1,2..k-2,n-1(从0开始计)。循环从倒数第二项开始决定他
应该所在的index的位置,直到正数第二项为止。中间的调整的过程有点复杂,可能可
以简化。下面是我随便写的代码。写得蛮差的,欢迎大家测试指正。
$k = 4;
$a = Array(1, 2, 5, 6, 11, 16, 17);
$records = Array();
for ($i = 1; $i < $k - 1; $i++)
{
$record = new Record($a[$i] - $a[$i - 1], $i);
$records[$i - 1] = $record;
}
$records[$k - 2] = new Record($a[count($a) - 1] - $a[$k - 2], count($a) - 1);
for ($last = $k - 2; $last > 0; $last--)
{
for ($i = $records[$la... 阅读全帖
f*******t
发帖数: 7549
21
来自主题: JobHunting版 - Exposed上一道string permutation的题
#include
#include
#include
#define BUFFSIZE 1024
using namespace std;
char buff[BUFFSIZE];
int idx;
void enumerate(const string& s, int pos)
{
if(pos == s.size()) {
if(idx == 0)
printf("{Empty}\n");
buff[idx] = 0;
printf("%s\n", buff);
}
else if(pos != 0 && s[pos] == s[pos-1]) {
enumerate(s, pos+1);
}
else {
buff[idx] = s[pos];
idx++;
enumerate(s, pos+1);
idx--;
enume... 阅读全帖
f*******t
发帖数: 7549
22
练习时写的,开方数支持小数和负数
double sqrt(double n)
{
if(n <= 0.0)
return 0.0;

double ans = n / 2.0;
int round = 0;
const double epsilon = 0.00001;
while(true) {
round++;
ans = (ans + n / ans) / 2;
double diff = ans * ans - n;
if(diff < 0)
diff = -diff;
if(diff < epsilon)
break;
}

//printf("Calculated %d rounds\n", round);

return ans;
}
double powerDouble(double a, double n) {
bool neg = fa... 阅读全帖
a******u
发帖数: 239
23
来自主题: JobHunting版 - c interview question
I think my answers to Question 7 and 8 are correct, but they said they are
not correct, why?
I already tested the code by Visual C++ (c compiler).
Thank you very much.
Line in file Contents
30 int * someIDs, theFirst, *r;
110 someIDs =GetSomeIDs(); /* defined below */
111 theFirst = someIDs [0];
112 r= ReorderIDs(someIDs);
113-150 /* we want to use ‘theFirst’ and ‘r’ here*/

499 /*-------- GetSomeIDs-----*/
500 int * GetSomeIDs()
501 {
502 int ids[8];
503-5... 阅读全帖
k***t
发帖数: 276
24
来自主题: JobHunting版 - 问个算法题
也来凑个热闹。主要是练练trie。
花了些时间才调通:( 谁帮忙给Review一下?谢了。
运行结果:
ad: 5
bc: 3
bb: 2
aaa: 1
aa: 1
源码:
#include
#include
using namespace std;
struct Node {
int cnt;
char c;
struct Node *n[26];
char *p; // to the 1st occurrence in the original input string
};
#define idx(x) (x-'a')
void add2trie (Node *r, char *p1, char *p2) {
char *p; Node *cur=r; Node *n;
p=p1;
cur=r;
while (p!=p2 && cur->n[idx(*p)]) {cur=cur->n[idx(*p)]; ++p;}
if (p==p2) { cur->cnt++;... 阅读全帖
f*******t
发帖数: 7549
25
平衡括号的题可以用贪心法做吧
#include
#include
#include
#include
#define INVALIDCHAR -1
using namespace std;
char *balance(char *str)
{
int len = strlen(str);
if(len < 1)
return NULL;

char *buff = (char*)calloc(len + 1, 1);
stack left;
for(int i = 0; i < len; i++) {
if(str[i] == '(')
left.push(i);
else if(str[i] == ')') {
if(left.empty()) {
buff[i] = INVALIDCHAR;
co... 阅读全帖
g*****1
发帖数: 998
26
来自主题: JobHunting版 - 请教一道c/c++题 (转载)
【 以下文字转载自 Programming 讨论区 】
发信人: guagua1 (), 信区: Programming
标 题: 请教一道c/c++题
发信站: BBS 未名空间站 (Fri Jan 27 22:47:12 2012, 美东)
char *m()
{
char str[50];
strcpy(str,"how are you");
return str;
}
int main()
{
char s[50];
strcpy(s,m());
printf("%s",s);
//cin.get();
return 0;
}
为什么结果可以正确输出呢?我知道return by pointer可以make copy,可是return之
后storage不是free了吗?
另外,为什么下面这个就只能由一部分正确输出?
char *m()
{
char str[20];
strcpy(str,"how are you");
return str;
}
int main()
{

printf("%s",m());
//cin.get();... 阅读全帖
w*******t
发帖数: 62
27
来自主题: JobHunting版 - 问个Print null的问题
为什么 1 和 2 的结果不同?
1. printf("%s\n", NULL);
结果: Segmentation fault (core dumped)
2. printf("add string %s\n", NULL);
结果: add string (null)
w*******t
发帖数: 62
28
来自主题: JobHunting版 - 问个Print null的问题
多谢!
查了一下 -fno-builtin-printf, 说是不把printf转换成puts。是这样吗?
可是要转都转,要么都不转。还是不明白1和2的结果为什么不同啊?
p*i
发帖数: 411
29
来自主题: JobHunting版 - 问个Print null的问题
By default a call to printf("%s\n", p) is converted at compile time to puts(
p) (it's faster).
That's why printf("%s", NULL) will succeed, since it won't be converted (
missing '\n').
a*****g
发帖数: 13
30
来自主题: JobHunting版 - facebook一题
c++ practice (use multiset):
#include
#include
using std::multiset;
using std::string;
int len_p = 4;
bool check_substr(string s, const multiset &L) {
multiset dup_L = L;
for (unsigned i=0; i string token = s.substr(i, len_p);
multiset::iterator itor = dup_L.find(token);
if (itor == dup_L.end()) {
return false;
}
dup_L.erase(itor);
}
return dup_L.empty();
}
int main(... 阅读全帖
a*****g
发帖数: 13
31
来自主题: JobHunting版 - facebook一题
c++ practice (use multiset):
#include
#include
using std::multiset;
using std::string;
int len_p = 4;
bool check_substr(string s, const multiset &L) {
multiset dup_L = L;
for (unsigned i=0; i string token = s.substr(i, len_p);
multiset::iterator itor = dup_L.find(token);
if (itor == dup_L.end()) {
return false;
}
dup_L.erase(itor);
}
return dup_L.empty();
}
int main(... 阅读全帖
a*****g
发帖数: 13
32
My solution:
1. build a graph by storing "possible next digits" for each digit.
2. dfs each digit in the graph.
#include
#include
using std::vector;
using std::string;
struct Node {
int value;
vector next;
Node(int v) {
value = v;
}
};
void build_tree(vector &input) {
for (unsigned i=0;i for (unsigned j=i+1;j if (input[i].value < input[j].value) {
input[i].next.p... 阅读全帖
s******n
发帖数: 3946
33
来自主题: JobHunting版 - leetcode上一题,求正解
写了几遍才对。。。
#include
#define exchangenum(a,b) {a^=b;b^=a;a^=b;}
void print(int* a, int count, int sum, int* out, int outindex)
{
if (sum==0) {
for (int i=0; i printf("\n");
return;
}
if (count==0) return;
out[outindex] = a[0];
print(a+1, count-1, sum-a[0], out, outindex+1);
print(a+1, count-1, sum, out, outindex);
}
int main(int argc, char** argv)
{
int a[5] = {1,3,4,2,6};
int sum = 7;
int out[5];
print(a, sizeof(a)/sizeof(a[0... 阅读全帖
s******n
发帖数: 3946
34
来自主题: JobHunting版 - leetcode上一题,求正解
如果有1,3,3,4,5,3重复,则需要特别处理,2个连续的3,分别处理3,3,4... 3,4... ,4.... 三种情况,应该没比我这程序更简短的了吧。:)
#include
void print(int* a, int count, int sum, int* out, int outindex)
{
if (sum==0) {
for (int i=0; i printf("\n");
return;
}
if (sum<0 || count==0) return;
int samea=1;
for (; samea for (int k=0; k<=samea; k++) {
print(a+samea, count-samea, sum-a[0]*(k), out, outindex+k);
out[outindex+k] = ... 阅读全帖
w*******s
发帖数: 96
35
Two implementation. one use sort and one use hash.
//pre: str is sorted.
void PermutationWithDuplicate(char *str, int position)
{
if (position == strlen(str)) {
printf("%s", str);
return;
}

char lastChar = '\0';
for (int i = position; i {
//skip those character which is duplicated. Since the string is
sorted, it's easy.
if (lastChar == str[i] ) continue;

lastChar = str[i];
swap(str[po... 阅读全帖
S****h
发帖数: 115
36
来自主题: JobHunting版 - 问一个G家面试题
贴下自己的代码供参考,大家有兴趣的话给挑挑ug,thanks!
import java.util.List;
class Solution {
List groups;
int score;
public Solution() {
groups = new ArrayList();
}
}
public class StringNumberGroup {
public Solution getOptimalGroup(String phone) {
if (phone.length() <= 3) {
Solution s = new Solution();
s.groups.add(phone);
s.score = getScore(phone);
... 阅读全帖
h*****f
发帖数: 248
37
来自主题: JobHunting版 - C++ template
1. Compile time because template initialization is done during the compile
time and the initialization is based on the "known" template parameter(s)
during the compile time.
2. A way to prove:
#include
#include
template class Buffer {
char internal[max];
public:
void printSize() {
printf("buffer size=%lu\n", sizeof(internal));
}
};
int main() {
Buffer<512> my512;
my512.printSize();
size_t v;
std::cin >> v;
printf("my input=%lu\... 阅读全帖
f*******t
发帖数: 7549
38
来自主题: JobHunting版 - find k missing numbers in range [0, N].
#include
#include
bool isSet(char *bitarray, int num)
{
int index = num / 8;
int offset = num % 8;
return bitarray[index] & (char)(1 << offset);
}
void set(char *bitarray, int num)
{
int index = num / 8;
int offset = num % 8;
bitarray[index] |= (char)(1 << offset);
}
void printMissingNum(int *array, int arraysize, int N)
{
int bitarraysize = (N + 7) / 8;
char *bitarray = (char*)calloc(bitarraysize, 1);
for(int i = 0; i < arraysize; ++i) {
... 阅读全帖
S******t
发帖数: 151
39
来自主题: JobHunting版 - 问个IQ 题
#include
#include
using namespace std;
char cross[3000][20];
int main()
{
int n,i,nc=0,sum=0,t[1000];
scanf("%d",&n);
for(i=0;i scanf("%d",&t[i]);
sort(t,t+n);
for(i=n-1;i>=3&&2*t[1] {
sprintf(cross[nc++],"%d %d\n",t[0],t[1]);
sprintf(cross[nc++],"%d\n",t[0]);
sprintf(cross[nc++],"%d %d\n",t[i-1],t[i]);
sprintf(cross[nc++],"%d\n",t[1]);
sum+=2*t[1]+t[0]+t[i];
}
for(;i>=2;i... 阅读全帖
W******g
发帖数: 887
40
debug的四种境界:
1. 入门:printf
2. 学生:IDE step-by-step
3. 专业:memory dump
4. 终极:printf
l****c
发帖数: 782
41
新手我试一下哈
typedef struct Node{
int value;
int level;
struct Node *left;
struct Node *right;
} node;
void_print(int LEVEL)
{
node *root;
if (LEVEL==0) return;
node *tmp = root;
queue.push(tmp);
stack.push(tmp);
while (queue.front()->level < LEVEL) {
int tmp_level = queue.front()->level;
while(queue.front()->level==tmp_level) {
node *tmp = queue.pop_front();
queue.push_back(tmp->left);
queue.push_back(tmp->right);
stack.push_back(tmp->left);
stack.push_back(tmp->right);
}
}
while(!stack.is... 阅读全帖
C***U
发帖数: 2406
42
void MorrisTraversal(struct tNode *root)
{
struct tNode *current,*pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
printf(" %d ", current->data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predeces... 阅读全帖
t*********h
发帖数: 941
43
来自主题: JobHunting版 - G phone interview
void foo(char* s) {
if(!*s) return;
int end[2], start[2], chars[2];
int maxlen=2,maxstart=0,i,n=strlen(s),p;
if(n<3) {printf("%s\n",s);}
start[0]=0;end[0]=0;chars[0]=s[0];
if(s[1]==s[0]) {
start[1]=0;end[1]=1;chars[1]=chars[0];
} else {
start[1]=1;end[1]=1;chars[1]=s[1];
}
for(i=2;i if(s[i]!=chars[0]&&s[i]!=chars[1]) {
p=end[0] chars[p]=s[i];
start[p]=i;
start[1-p]=end[p]+1;
end[p]=i;
} else {
p=(chars[0]=... 阅读全帖
l**h
发帖数: 893
44
搜索了一下,网上一种常见的解法如下:pathLen一直增加,不断把节点的值加进去。
我怎么觉得有错, 比如
1
/ \
2 3
\ /\
4 5 6
打印出来岂不是
1, 2, 4
1, 2, 4, 3, 5
1, 2, 4, 3, 6
了?
http://k2code.blogspot.com/2011/05/root-to-leaf-path.html
/*
Given a binary tree, print out all of its root-to-leaf
paths, one per line. Uses a recursive helper to do the work.
*/
void printPaths(struct node* node) {
int path[1000]; printPathsRecur(node, path, 0);
}
/*
Recursive helper function -- given a node, and an array containing
the path from the r... 阅读全帖
w****a
发帖数: 710
45
举个例子,
比如你在写一个脚本解析器,你编译脚本过程中检查脚本是否有语法错误。但是你的检
查机制可能在很多初。如果你每次检查到语法错误的时候仅仅是打印下错误信息,这个
显然不行,因为你可能不需要打印信息而是要返回具体的错误描述,要写到日志里。如
果仅仅是return,这个也不行,你在你的解析器里return,外面也不知道。如果是传统
方法的话,一般可以写到一个全局的错误收集器里,可以通过GetLastError之类的函数
来获取上一次出错的错误编号和具体内容。这个是传统做法。
如果使用exception机制,查到错误时直接抛出异常。你抛出异常,可以由不同的地方
catch。catch后可以随意处理,可以跳过,也可以直接警告输出个消息,也可以崩溃。
比如上面的例子:
try{
script_parser.parse(script);
}catch(XXXScriptExcept& e){
printf(e.what());
}
传统做法的代码是:
int err = script_parser.parse(script);
if(err!=0){
printf(G... 阅读全帖
i****1
发帖数: 445
46
来自主题: JobHunting版 - 比较两个两个浮点数
float f = 1.23;
double d = 1.23;
if (f == d) printf("equal");
else printf("not equal");
这个我在vs 32位系统,64位cpu上结果为:not equal。如果把1.23换成1.25就是“
equal".
这个怎么分析?
s********r
发帖数: 403
47
不知道下面这种满不满足你的需求
一般来讲,宏函数短小,主要还是靠精确的设计不靠debug
$ cat macro.c
#include
#define PRINT(str) \
do \
{ \
int i = 1; \
printf("%s %dn", (str), i); \
} \
while (0);
int main(void)
{
const char *sz_in = "Hello";
PRINT(sz_in);
return 0;
}
gcc -ggdb3 macro.c
(gdb) info MACRO PRINT
Defined at /usr/local/src_test/macro.c:3
#define PRINT(str) do { int i = 1; printf("%s %dn", (str), i); } while (0);
(gdb) si
0x0000000000400540 15 PRINT(sz_in);
(gdb) p i
$1 = 1
(gdb) p sz_in... 阅读全帖
d******b
发帖数: 73
48
来自主题: JobHunting版 - 问个基础题,大家不要笑我
这个问题可能涉及 printf 的实现,这有一篇供参考,但是太偏了 直接 cout << f 或
者 printf("...", (int)f) 不好么?
http://www.cnblogs.com/XiaoHDeBlog/p/3327723.html
l***p
发帖数: 358
49
来自主题: JobHunting版 - linkedin,rocketfuel, google面经若干
中间有0的情况,比如
10042319
#include
int main(int argc, char * argv[])
{
int num = atoi(argv[1]);
char s[] = "45002319";
printf("source: %s and num:%d", s, num);
size_t size;
while (num > 0 && (s && (size = strlen(s)) > 0))
{
if (size > 1)
{
if (s[0] > s[1])
{// 4[<4, 0]
size_t cz = 1;
char * n = s + 1;
... 阅读全帖
f****r
发帖数: 15
50
来自主题: JobHunting版 - FLAGBR 面经+offer
bool array[101] = {false};
for (int skip = 1; skip <= 100; skip++) {
for (int i = 0; i <= 100; i += skip) {
array[i] = !array[i];
}
}
printf("index 12: %sn", array[12] ? "true" : "false");
printf("index 9: %sn", array[9] ? "true" : "false");
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)