您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
如果不用循环、递归、goto,如何才能用 C++ 从 1 打印到 100 ?
看到这样一篇文章。上面有很多种解法,下面介绍几个好理解一点的:
第一种:在代码中执行系统指令
#include <stdlib.h>
int main() {
return system("seq 1 100");
}第二种:利用信号捕捉
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
int i = 0;
void sig_alarm_handler(int signal) {
++i;
printf("%dn", i);
if(i < 100)
alarm(1);
else
exit(0);
}
int main() {
signal(SIGALRM, sig_alarm_handler);
alarm(1);
int x;
scanf(" %d",&x);
return 0;
}第三种:利用模板参数与继承特性
#include <stdio.h>
template<int N>
struct X : X<N-1> {
X() { printf("%dn", N); }
};
template<>
struct X<0> {};
int main() {
X<100> x;
return 0;
}第四种:用静态变量和数组
#include <stdio.h>
struct X {
static int i;
X() { ++i; printf("%dn", i); }
};
int X::i = 0;
int main() {
X arr[100];
return 0;
}就看懂了这几种,感觉简直太神奇了!












免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。