Problem 1. Find the Bugs (5 points each)
The following routines each have one bug. Correct each one.
a. This function is supposed to append string_tail to the end of string_head without using the strcat() function. It assumes that string_head has enough room to contain the result.
Код:
char* AppendString(char* string_head, char* string_tail)
{
int length;
length = strlen(string_tail);
strcpy(string_head + length, string_tail);
return string_head;
}
Problem 1. Find the Bugs
b. String Look-up
This function returns the look-up table string given a key. Passing the string “tofu” should return a pointer to “soy beans”. Passing the string “chickens” should return a NULL pointer.
Свернуть исходник
Код:
static char* arrayLookup[] =
{
"eggs", "chickens",
"tofu", "soy beans",
"coriander", "cilantro",
"yeast", "wheat"
};
char* LookupString(char* string_key)
{
char** strIndex;
for (strIndex = arrayLookup; strIndex; strIndex += 2)
{
if (!strcmp(*strIndex, string_key))
{
return strIndex[1];
}
}
return NULL;
}
Problem 1. Find the Bugs
c. This function accepts an MS-DOS pathname string, which is of the form
drive_letter:\directory\...\directory\filename.extension
It returns a pointer to the start of the base filename. For example, given the string “c:\source\graph\spin.c” it returns a pointer to the character “s” in “spin”.
Свернуть исходник
Код:
char* FindBasename(char* string_filename)
{
int i;
/* Look for the beginning of the filename: */
for (i = strlen(string_filename); i; i--)
{
switch (string_filename)
{
case ':': /* Look for path separators */
case '\\':
break; /* Quit when one is found */
}
}
/* Return a pointer to the filename: */
return string_filename + i;
}
Problem 1. Find the Bugs
d. This function initializes each element of an array to contain its own index.
Код:
void InitArray(int* array, int array_length)
{
int i = 0;
while (i < array_length)
{
array = i++;
}
}
Problem 2. High Quality Code (10 points each)
Rewrite the following code fragments to turn them into production-quality code. (Don’t forget that good code includes comments.)
a. Machine-Dependence and Non-Portability:
This function finds the centroid, or average, of two two-dimensional points A and B:
Код:
long Centroid(long A, long B)
{
int x, y;
x = ((int) (A >> 16) + (int) (B >> 16)) / 2;
y = ((int) A + (int) B) / 2;
return ((long) x << 16) + y;
}
Problem 2. High Quality Code
b. Error Checking:
This function reads a string, preceded by a two-byte length, from a file into a C-style string in memory.
char *ReadStringFromFile(FILE *fp)
{
char *str;
int length;
fread(&length, 2, 1, fp);
str = malloc(length + 1);
fread(str, 1, length, fp);
str[length] = 0;
return str;
}
Problem 3. Linked-List enhancement (30 points)
Given the data structure item as an item in a linked list, write the function AddKey() to add a node to the list. Maintain the list sorted by key.
Include a comment describing how the function behaves, your assumptions, and the return value from the function. Be sure to think about special cases and possible errors
Код:
typedef struct _NODE
{
struct _NODE *node_next;
int key;
char *data;
} ITEM, *NODE, *LIST;
LIST AddKey (LIST list, int key, char* data);
Problem 4. Loop Optimization (Bonus — 10 points. Do the other problems first.)
Rewrite the function for fast execution. Assume that the compiler makes no op¬timizations and generates code literally from the source. Do not use register variables.
Свернуть исходник
Код:
char* SlowFunction(char* output, char* input)
{
int i, j;
for (i = 0, j = 0; input; ++i)
{
if (input >= ' ' && input < 'a')
{
output[j++] = input;
}
if (input >= 'a' && input <= 'z')
{
output[j++] = input - ('a' - 'A');
}
if (input > 'z' && input[i] < 0x7f)
{
output[j++] = input[i];
}
}
output[j] = '\0';
return output;
}
Помогите с решением задач
Модераторы: Hawk, Romeo, Absurd, DeeJayC, WinMain
Такое надо размещать в "Решите мне задачку". Потому что это не "помогите", а "решите за меня, я даже не удосужусь перевести задание с английского".
По теме - брать предлагаемый код, запихивать в компилятор, запускать, смотреть, что возвращает. Как минимум с этого можно начать.
По теме - брать предлагаемый код, запихивать в компилятор, запускать, смотреть, что возвращает. Как минимум с этого можно начать.
Искусство программирования - заставить компьютер делать все то, что вам делать лень.
Для "спасибо" есть кнопка "Спасибо" в виде звездочки внизу под ником автора поста.
Для "спасибо" есть кнопка "Спасибо" в виде звездочки внизу под ником автора поста.
-
- Сообщения: 1
- Зарегистрирован: 07 сен 2013, 20:32
Помогите пожалуйста, задание такое: Вычислить максимальное значение сгенерированной последовательности случайных чисел в диапазоне от 0 до 50.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(NULL));
int max =0;
int n =0;
cin>>n;
int **a= new int* [n];
for(int i=0;i<n; i++)
{
a=new int [n];
}
for(int i=0;i<n;i++)
{
a=rand()%(50-0+1)-0; ---- здесь выдает ошибку
cout<<a<<" ";
}
cout<<endl;
max=a[0];
for(int i=0;i<n;i++){
if(a[0]>max){
a=max;}
cout<<"max="<<a<<endl;
}
system("PAUSE");
return 0;
}
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand(time(NULL));
int max =0;
int n =0;
cin>>n;
int **a= new int* [n];
for(int i=0;i<n; i++)
{
a=new int [n];
}
for(int i=0;i<n;i++)
{
a=rand()%(50-0+1)-0; ---- здесь выдает ошибку
cout<<a<<" ";
}
cout<<endl;
max=a[0];
for(int i=0;i<n;i++){
if(a[0]>max){
a=max;}
cout<<"max="<<a<<endl;
}
system("PAUSE");
return 0;
}
a=new int [n]; // a - это массив целых чисел ил n элементов
rand()%(50-0+1)-0; // это целое число
присвоить массиву значение числа нельзя (конфликт типов)
Да и весь код неверный (поиск максимума тоже)
rand()%(50-0+1)-0; // это целое число
присвоить массиву значение числа нельзя (конфликт типов)
Да и весь код неверный (поиск максимума тоже)
Приглашаю на свой блог о программировании: pro-prof.com
А я вообще не понимаю зачем здесь нужны массивы
It's a long way to the top if you wanna rock'n'roll