付録
課題1の付録
C 言語
#include <stdio.h>
#include <stdlib.h>
void usage(char * cmd){
fprintf(stderr,"usage: %s ninzu\n",cmd);
}
int main(int ARGC, char* ARGV[]){
int ninzu;
if(ARGC!=2){
usage(ARGV[0]);
return 1;
}
ninzu=atoi(ARGV[1]);
if(ninzu<=0){
usage(ARGV[0]);
return 1;
}
printf("%d\n",ninzu);
return 0;
}
C++
#include <iostream>
#include <string>
int getNinzu(int ARGC, char *ARGV[]) throw (char const *){
if(ARGC!=2){
throw "Needs only one argument.";
}
int ninzu=std::atoi(ARGV[1]);
if(ninzu<=0){
throw "Value is too small.";
}
return ninzu;
}
int main(int ARGC, char* ARGV[]){
std::string cmdname=ARGV[0];
int ninzu;
try{
ninzu=getNinzu(ARGC,ARGV);
}catch(char const *str){
std::cerr << str << std::endl
<< "Usage: " << cmdname << " ninzu" << std::endl;
return 1;
}
std::cout << ninzu << std::endl;
}
Java
class Test {
private static int getNinzu(String str)
throws NumberFormatException,
IllegalArgumentException {
int value = Integer.valueOf(str);
if(value<=0){
throw new IllegalArgumentException();
}
return value;
}
public static void main(String[] arg){
String cmdname="Test";
int ninzu;
try{
ninzu=getNinzu(arg[0]);
}catch(Exception e){
System.err.println(e.getClass().getName());
System.err.println("Usage: "+cmdname+" ninzu");
return ;
}
System.out.println(ninzu);
}
}
C言語
#include <stdio.h>
int main(void){
printf("%05d\n",1);
return 0;
}
C++
#include <iostream>
#include <iomanip>
int main(){
std::cout << std::setw(5)
<< std::setfill('0')
<< 1
<< std::endl;
}
Java
class Pad {
public static void main(String[] args){
System.out.println(String.format("%05d",1));
}
}
C言語
#include <stdlib.h>
#include <time.h>
int myrand(void){
static int firsttime=1;
if(firsttime){
firsttime=0;
srand(time(NULL));
}
return (int)((double)rand()/(RAND_MAX+1.0)*(5+1));
}
C++
#include <cstdlib>
#include <ctime>
int randfive(){
static bool firsttime=true;
if(firsttime){
firsttime=false;
std::srand(std::time(NULL));
}
return static_cast<int>(static_cast<double>(std::rand())/(RAND_MAX+1.0)*(5+1));
}
Java
public class MyRand {
public static int get(){
return (int) (Math.random()*(5+1));
}
}
坂本直志 <sakamoto@c.dendai.ac.jp>
東京電機大学工学部情報通信工学科