Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
17
Добавлен:
16.04.2013
Размер:
12.5 Кб
Скачать
/*	
	Использовать комментарии для выделения задачи	
*/

// Задача 1.1 Первая программа 
// ----------------------------

/*#include <iostream>

int main()
{
	std::cout << "Welcome to C++!\n";
	return 0;   
}
*/
                                            
// Задача 1.2 Печать составной строки 
// -----------------------------------

/*#include <iostream>

int main()
{
	std::cout << "Welcome ";      // Программист - кретин, ибо только он может специально
	std::cout << "to C++!\n";     // переключиться на русский язык, чтоб сделать западло :)
	return 0;
}
*/

// Задача 1.3	Печать в две строки ----------------------

/*
#include <iostream>

int main()
{
	std::cout << "Welcome\nto C++!\n"; // А еще он попутал ":" с ";"
	                                 // и не умеет считать "\n"!
	return 0;   
}
*/

// Задача 1.4	Программа сложения ---------------------------------------------------------

/*#include <iostream>

int main()
{
	int integer1, integer2, sum;           

	std::cout << "Enter first integer\n";  
	std::cin >> integer1;                  // А точку с запятой не забыли?!
	std::cout << "Enter second integer\n"; 
	std::cin >> integer2;                  
	sum = integer1 + integer2;             
	std::cout << "Sum is " << sum << std::endl; // За правописанием следи!

   return 0;  
}
*/

// Задача 1.5	Использование деклараций, операторов отношений и эквивалентности ------------

/*#include <iostream> // В MSVC iostream - не хедер-файл, а модуль!

using std::cout;  
using std::cin;   
using std::endl;  

int main()
{
   int num1, num2;

   cout << "Enter two integers, and I will tell you\n" 
        << "the relationships they satisfy: ";
   cin >> num1 >> num2; // Точка с запятой...

   if ( num1 == num2 )
      cout << num1 << " is equal to " << num2 << endl;

   if ( num1 != num2 )
      cout << num1 << " is not equal to " << num2 << endl;

   if ( num1 < num2 )
      cout << num1 << " is less than " << num2 << endl;

   if ( num1 > num2 )   // Идиотская ошибка в правописании
      cout << num1 << " is greater than " << num2 << endl;

   if ( num1 <= num2 ) 
      cout << num1 << " is less than or equal to "
           << num2 << endl;

   if ( num1 >= num2 ) // Букву U на букву И заменить - это уже верх западлостроения... :)
			cout << num1 << " is greater than or equal to "
           << num2 << endl;

   return 0;   
}
*/

// Задача 1.6 
// Class average program with counter-controlled repetition
/*#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
   int total,        // sum of grades 
       gradeCounter, // number of grades entered
       grade,        // one grade
       average;      // average of grades

   // initialization phase
   total = 0;                           // clear total
   gradeCounter = 1;                    // prepare to loop

   // processing phase
   while ( gradeCounter <= 10. ) {      // loop 10 times
      cout << "Enter grade: ";          // prompt for input
      cin >> grade;                     // input grade   // опять правописание хромает
      total += grade;            // add grade to total // а я бы написал +=
      ++gradeCounter;  // increment counter // а тут бы ++
   }

   // termination phase
   average = total / 10;                // integer division
   cout << "Class average is " << average << endl; // а по-моему, L не похожа на единицу...

   return 0;   // indicate program ended successfully
}
*/

// Задача 1.7 
// Class average program with sentinel- controlled repetition.
/*#include <iostream>

using std::cout;
using std::cin;
using std::endl;
using std::ios;

#include <iomanip>

using std::setprecision;
using std::setiosflags;

int main()
{
   int total,        // sum of grades
       gradeCounter, // number of grades entered
       grade;        // one grade       
   double average;   // number with decimal point for average

   // initialization phase
   total = 0;
   gradeCounter = 0;  // дурацкая ошибка - пропустили "е". Как всегда...

   // processing phase
   cout << "Enter grade, -1 to end: ";    
   cin >> grade;                         

   while ( grade != -1 ) {  // нет оператора ! =, а есть оператор !=
      total += grade;              // то же что и раньше
      ++gradeCounter;              // аналогично
      cout << "Enter grade, -1 to end: "; 
      cin >> grade;      // в сишнике маленькие и большие буквы отличаются!
   }

   // termination phase
   if (gradeCounter) {  // !=0 не обязательно, оно и так TRUE, если !=0
      average = static_cast< double >( total ) / gradeCounter;   
      cout << "Class average is " << setprecision( 2 )
           << setiosflags( ios::fixed | ios::showpoint )
           << average << endl;
   }
   else
      cout << "No grades were entered" << endl;

   return 0;   // indicate program ended successfully
}
*/


// Задача 1.8
// Analysis of examination results
/*#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
   // initialize variables in declarations
   int passes = 0,           // number of passes
       failures = 0,         // number of failures
       studentCounter = 1,   // student counter
       result;               // one exam result

   // process 10 students; counter-controlled loop
   while ( studentCounter <= 10 ) { // у вас клавиатура что ли не работает?! Я насчет t...
	   // А еще 1 не в восьмеричной системе в ассемблере, а скорее всего 10...
      cout << "Enter result (1=pass,2=fail): ";
      cin >> result;

      if ( result == 1 )      // if/else nested in while
         passes = passes + 1; // точно клава не работает... :)
      else
         failures = failures + 1;

      studentCounter = studentCounter + 1;
   }

   // termination phase
   cout << "Passed " << passes << endl;
   cout << "Failed " << failures << endl;

   if ( passes > 8 )
      cout << "Raise tuition " << endl;

   return 0;   // successful termination
}
*/

// Задача 1.9
// Preincrementing and postincrementing

/*#include <iostream> // хотел бы я посмотреть на того, кто найдет модуль IOSTREAN...

using std::cout;
using std::endl;

int main()
{
   int c;

   c = 5;
   cout << c << endl;         // print 5
   cout << c++ << endl;       // print 5 then postincrement
   cout << c << endl << endl; // print 6

   c = 5;
   cout << c << endl;         // print 5
   cout << ++c << endl;       // preincrement then print 6
   cout << c << endl;         // print 6

   return 0;                  // successful termination
   // и где же обещанные семантические ошибки? Я в вас разочаровался, дорогие заподлянщики... :)
}
*/
// Задача 1.10	Вывод последовательности "while"
// ------------------------------------------------------
/*#include <iostream>

using std::cout;
using std::endl;

int main()
{
   int counter = 1;             // initialization

   while ( counter <= 10 ) {    // repetition condition
      cout << counter << endl; // опять ваш couter.........
      ++counter;                // increment
   }
   return 666; // А return куда фашисты утащили? :)
}
*/
// Задача 1.11	Вывод последовательности "for"
// ----------------------------------------------------
/*#include <iostream>

using std::cout;
using std::endl;

int main()
{
   for ( int counter = 1; counter <= 10; counter++ )
      cout << counter << endl;

   return 0;
} // А по-моему, тут все правильно работает...
*/
// Задача 1.11	Суммирование с оператором "for"
// -----------------------------------------------------
/*#include <iostream>

using std::cout; // А вторая одинадцатая задача - это тоже глюк? :)
using std::endl;

int main()
{
   int sum = 0;

   for ( int number = 2; number <= 100; number += 2 )
      sum += number; // numbe - это конечно классно звучит :)

   cout << "Sum is " << sum << endl;

   return 0;
}
*/
// Задача 1.12	Вычисление сложных процентов
// -------------------------------------------
/*#include <iostream>

using std::cout;
using std::endl;
using std::ios;

#include <iomanip>

using std::setw;
using std::setiosflags;
using std::setprecision;

#include <cmath>

int main()
{
   double amount,              // amount on deposit
          principal = 1000.0,  // starting principal
          rate = .05;          // interest rate

   cout << "Year" << setw( 21 ) 
        << "Amount on deposit" << endl;

   // set the floating-point number format
   cout << setiosflags( ios::fixed | ios::showpoint ) // а по-моему setiosflags и setprecision
        << setprecision( 2 );

   for ( int year = 1; year <= 10; year++ ) {
      amount = principal * pow( 1.0 + rate, year );
      cout << setw( 4 ) << year << setw( 21 ) << amount << endl;
   }

   return 0;
}
*/
// Задача 1.13 
// Counting letter grades
/*#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
   int grade,       // one grade
       aCount = 0,  // number of A's
       bCount = 0,  // number of B's
       cCount = 0,  // number of C's
       dCount = 0,  // number of D's
       fCount = 0;  // number of F's

   cout << "Enter the letter grades." << endl
        << "Enter the EOF character to end input." << endl;

   while ( ( grade = cin.get() ) != EOF ) {

      switch ( grade ) {      // switch nested in while

         case 'A':  // grade was uppercase A // Не, ну я так не могу. Специально ставить
         case 'a':  // or lowercase a // русские буквы вместо английских - это не мой стиль :Е
            ++aCount;         
            break;  // necessary to exit switch

         case 'B':  // grade was uppercase B
         case 'b':  // or lowercase b
            ++bCount;         
            break;

         case 'C':  // grade was uppercase C
         case 'c':  // or lowercase c
            ++cCount;         
            break;

         case 'D':  // grade was uppercase D
         case 'd':  // or lowercase d
            ++dCount;         
            break;

         case 'F':  // grade was uppercase F
         case 'f':  // or lowercase f
            ++fCount;         
            break;

         case '\n': // ignore newlines,  
         case '\t': // tabs, 
         case ' ':  // and spaces in input
            break;

         default:   // catch all other characters
            cout << "Incorrect letter grade entered."
                 << " Enter a new grade." << endl;
            break;  // optional
      }
   }

   cout << "\n\nTotals for each letter grade are:" 
        << "\nA: " << aCount 
        << "\nB: " << bCount 
        << "\nC: " << cCount 
        << "\nD: " << dCount
        << "\nF: " << fCount << endl;

   return 0;
}
*/
// Задача 1.14
// Using the do/while repetition structure

/*#include <iostream>

using std::cout;
using std::endl;

int main()
{
   int couter = 1; // Хотите couter? Будет вам couter вместо counter-а, хотя я думаю,
   // подразумевалось обратное. А я так сделаю, чтобы виндо было, что можно пойти и другим
   // путем :)

   do {
      cout << couter << "  ";
   } while ( ++couter <= 10 );

   cout << endl;

   return 0;
}
*/
// Задача 1.15
// Using the break statement in a for structure
/*#include <iostream> // а здесь я ошибок не нашел...

using std::cout;
using std::endl;

int main()
{
   // x declared here so it can be used after the loop
   int x; 

   for ( x = 1; x < 10; x++ ) {

      if ( x == 5 )
         break;    // break loop only if x is 5

      cout << x << " ";
   }

   cout << "\nBroke out of loop at x of " << x << endl;
   return 0;
}
*/
// Задача 1.16
// Using the continue statement in a for structure
/*#include <iostream>

using std::cout;

int main()
{
	for ( int x = 1; x <= 10; x++ ) { // нельзя сравнивать переменную в определении

      if ( x == 5 ) // x у нас целый, поэтому тайпкаст float=>int нам незачем. Забьем на точку
         continue;  // skip remaining code in loop
                    // only if x is 5

      cout << x << " ";
   }

   cout << "\nUsed continue to skip printing the value 5" 
       << std::endl; // Нужно прямо ссылаться на класс std, либо писать using...
   return 0;
}
*/
Соседние файлы в папке Лабы 4 семестр