高级语言程序设计第八次个人作业

高级语言程序设计第八次个人作业


作业内容

编写并运行书本第11章11.13编程练习题目中的第1~3,6,7题。

  • (1)设计并测试一个函数,从输入中获取n个字符(包括空白、制表符、换行符),把结果存储在一个数组里,它的地址被传递作为一个参数
#include<stdio.h>
#include<string.h>
#define max_size 100
void get(char *c,int n);
int main(){
  char cc[max_size];
  int n;
  printf("请输入获取字符数n和字符:");
   scanf("%d",&n);
   get(cc,n);
   printf("读取字符为\n"); 
   for (int i=0;i<n;i++){
    	printf("%c",cc[i]);        
	}     
  return 0;
}
void get(char *c,int n) {
    for (int i=0;i<n;i++){
    	 *c++=getchar();          
	}     
}

屏幕截图 2025-12-07 211359

  • (2)修改并编程练习一的函数,在n个字符后停止,或在读到第一个空白,制表符,换行符时停止,哪个先遇到哪个停止,不能只使用scanf()
#include <stdio.h>
#include <string.h>
#define max_size 100
void get(char *c, int n);
int main() {
    char cc[max_size];
    int n;
    printf("请输入获取字符数n和字符:");
    scanf("%d", &n);
    while (getchar() != '\n') {         // 清除输入缓冲区中的换行符
        continue;
    }
    get(cc, n);
    printf("读取字符为:\n"); 
    for (int i = 0; i < n && cc[i] != '\0'; i++) {
        printf("%c", cc[i]);        
    }
    printf("\n");
    
    return 0;
}

void get(char *c, int n) {
    int i = 0;
    char ch;
    while (i < n) {
        ch = getchar();
        if (ch == ' ' || ch == '\t' || ch == '\n') {             // 如果遇到空白字符、制表符或换行符,则停止读取
            break; 
        }
        
        c[i] = ch;
        i++;
    }
    if (i < n) {           // 在字符串末尾添加结束符
        c[i] = '\0';
    } else if (i == n) {
        c[i] = '\0';
    }
}

屏幕截图 2025-12-08 141238

  • (3)设计并测试一个函数,从一行输入中把一个单词读入一个数组中,并丢弃输入行中其余字符。该函数应该跳过第一个非空白字符前的所有空白。将一个单词定义为没有空白,制表符或换行符的字符序列。
#include<stdio.h>
#include<string.h>
#define max_size 100
void get(char *c);
int main(){
  char cc[max_size];
  printf("请输入单词:");
   get(cc);
   printf("读取单词为:%s",cc); 
   
  return 0;
}
void get(char *c) {
	scanf("%s",c); 
}

屏幕截图 2025-12-07 220025

  • (6)编写一个名为is_within()的函数,接受一个字符和一个指向字符串的指针作为两个函数的形参。如果指定字符在字符串中,该函数返回一个非零值(即为真)。否则,返回0(即为假)。在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。
#include<stdio.h>
#include<string.h>
#define max_size 100
int is_within(const char *c,char x);
int main(){
  const char *sp="point";
  char x;
  printf("请输入查找的字符\n");
  scanf("%c",&x);	
  while(!is_within(sp,x)){
  	while(getchar()!='\n');           //清除缓冲区
  	printf("%c不在其中请重新输入\n",x);
    scanf("%c",&x);	
  }
  printf("%c在其中",x);
   
  return 0;
}
int is_within(const char *c,char x) {
	while(*c){
		if(*c++==x){
			return 1;
		}
		
	} 
	return 0;
}

屏幕截图 2025-12-07 224545

  • (7)strncpy(s1,s2,n)函数把s2中的n个字符拷贝值s1中,截断s2,或者有必要的话在末尾添加空字符。如果s2的长度是n或多于n,目标字符串不能以空字符结尾。该函数返回s1。编写一个名为mystrncpy()的函数在一个完整的程序中测试该函数,使用一个循环给函数提供输入值。
#include <stdio.h>
#include <string.h>

char *mystrncpy(char *s1, const char *s2, size_t n);

int main(void) {
    char s2[100];         // 源字符串
    char s1[100];        // 目标字符串
    int n;
    printf("输入源字符串 s2 (输入 'quit' 退出): ");
    
    while (scanf("%s", s2) == 1 && strcmp(s2, "quit") != 0) {
        printf("输入要复制的字符数 n: ");
        scanf("%d", &n);
       
        mystrncpy(s1, s2, n);
        s1[99] = '\0';            // 确保以空字符结尾
        
        printf("复制结果: %s\n", s1);
        printf("详细内容 (字符ASCII值): ");                // 显示s1的每个字符(包括空字符)
        for (int i = 0; i <= n && i < 10; i++) {
            if (s1[i] == '\0') {
                printf("'\\0'(0) ");
            } else {
                printf("'%c'(%d) ", s1[i], s1[i]);
            }
        }
        printf("\n");
        
        printf("\n输入下一个源字符串 s2 (输入 'quit' 退出): ");
    }
    
    printf("程序结束\n");
    return 0;
}

char *mystrncpy(char *s1, const char *s2, size_t n) {
    char *p = s1;             // 保存起始地址
    while (n > 0 && *s2 != '\0') {
        *s1 = *s2;
        s1++;
        s2++;
        n--;
    }
    
    while (n > 0) {             // 如果n>0,用空字符填充剩余空间
        *s1 = '\0';
        s1++;
        n--;
    }
    return p;  
}


屏幕截图 2025-12-08 143222

编写并运行书本第12章12.9编程练习题目中的第1~3,8,9题。

  • (1)不使用全局变量,重写程序清单12.4
#include<stdio.h>

void critic( int *x);
int main(){
	int units =0;
  
  char x;
  printf("How many pounds to a firkin of butter?\n");
  scanf("%d",&units);	
  while(units!=56){
  	critic(&units);
  }
  printf("You must have look it up!\n");
   
  return 0;
}
void critic(int *x){
	printf("No luck,my friend.Try again.\n");
	scanf("%d",x);
}

屏幕截图 2025-12-07 231108

  • (2)
//pe12-2a.h 头文件
#ifndef PE12_2A_H
#define PE12_2A_H

// 函数声明
void set_mode(int mode);
void get_info(void);
void show_info(void);

#endif
//pe12-2a.c 源文件
#include <stdio.h>
#include "pe12-2a.h"

// 文件作用域、内部链接的变量
static int mode = 0;           // 0=公制, 1=美制,默认为公制
static double distance = 0.0;  // 行驶距离
static double fuel = 0.0;      // 消耗的燃料

// 设置模式,处理无效输入
void set_mode(int new_mode)
{
    if (new_mode == 0 || new_mode == 1) {
        mode = new_mode;
    } else {                                        // 使用上一次的有效模式
        printf("Invalid mode specified. ");                  
        if (mode == 0) {                                 
            printf("Mode 0 (metric) used.\n");
        } else {
            printf("Mode 1 (US) used.\n");
        }
    }
}

// 根据模式获取用户输入
void get_info(void)
{
    if (mode == 0) {                 // 公制模式
        printf("Enter distance traveled in kilometers: ");
        scanf("%lf", &distance);
        printf("Enter fuel consumed in liters: ");
        scanf("%lf", &fuel);
    } else {                     // 美制模式
        printf("Enter distance traveled in miles: ");
        scanf("%lf", &distance);
        printf("Enter fuel consumed in gallons: ");
        scanf("%lf", &fuel);
    }
}

// 根据模式计算并显示油耗
void show_info(void)
{
    if (mode == 0) {                    // 公制: 升/100公里
        if (distance != 0) {
            double consumption = (fuel / distance) * 100;
            printf("Fuel consumption is %.2f liters per 100 km.\n", consumption);
        } else {
            printf("Distance cannot be zero.\n");
        }
    } else {                            // 美制: 英里/加仑
        if (fuel != 0) {
            double consumption = distance / fuel;
            printf("Fuel consumption is %.2f miles per gallon.\n", consumption);
        } else {
            printf("Fuel consumed cannot be zero.\n");
        }
    }
}

  • (3)改编上题,使用自动变量
////pe12-2a.h 头文件
#define _CRT_SECURE_NO_WARNINGS
#ifndef PE12_2A_H
#define PE12_2A_H

// 模式常量
#define METRIC 0
#define US 1

// 函数声明 
void set_mode(int* mode, int new_mode);
void get_info(int mode, double* distance, double* fuel);
void show_info(int mode, double distance, double fuel);

#endif

#pragma once
//pe12-2a.c 源文件
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "pe12-2a.h"


// 设置模式&处理无效输入
void set_mode(int* mode, int new_mode)
{
    if (new_mode == METRIC || new_mode == US) {
        *mode = new_mode;
    }
    else {                          // 使用上一次的有效模式
        printf("Invalid mode specified. ");
        if (*mode == METRIC) {
            printf("Mode %d (metric) used.\n", METRIC);
        }
        else {
            printf("Mode %d (US) used.\n", US);
        }
    }
}

// 根据模式获取用户输入
void get_info(int mode, double* distance, double* fuel)
{
    if (mode == METRIC) {                 //公制模式 
        printf("Enter distance traveled in kilometers: ");
        scanf("%lf", distance);
        printf("Enter fuel consumed in liters: ");
        scanf("%lf", fuel);
    }
    else {                            // US模式
        printf("Enter distance traveled in miles: ");
        scanf("%lf", distance);
        printf("Enter fuel consumed in gallons: ");
        scanf("%lf", fuel);
    }
}

// 根据模式计算并显示油耗
void show_info(int mode, double distance, double fuel)
{
    if (mode == METRIC) {               // 公制: 升/100公里
        if (distance != 0) {
            double consumption = (fuel / distance) * 100;
            printf("Fuel consumption is %.2f liters per 100 km.\n", consumption);
        }
        else {
            printf("Distance cannot be zero.\n");
        }
    }
    else {                         // 美制: 英里/加仑
        if (fuel != 0) {
            double consumption = distance / fuel;
            printf("Fuel consumption is %.2f miles per gallon.\n", consumption);
        }
        else {
            printf("Fuel consumed cannot be zero.\n");
        }
    }
}

//主函数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "pe12-2a.h"

int main(void)
{
    int mode = US;  // 当前模式,初始为美制模式(根据示例输出)
    int new_mode;   // 用户输入的新模式
    double distance = 0.0;
    double fuel = 0.0;

    printf("Enter 0 for metric mode, 1 for US mode: ");
    scanf("%d", &new_mode);

    while (new_mode >= 0)
    {
        // 设置模式(处理无效输入)
        set_mode(&mode, new_mode);

        // 获取用户输入的距离和燃料数据
        get_info(mode, &distance, &fuel);

        // 计算并显示油耗
        show_info(mode, distance, fuel);

        printf("Enter 0 for metric mode, 1 for US mode (-1 to quit): ");
        scanf("%d", &new_mode);
    }

    printf("Done.\n");
    return 0;
}

屏幕截图 2025-12-08 135048

  • (8)
#include <stdio.h>
#include <stdlib.h>  

int * make_array(int elem, int val);
void show_array(const int ar[], int n);

int main(void)
{
    int * pa;
    int size;
    int value;

    printf("Enter the number of elements: ");
    while (scanf("%d", &size) == 1 && size > 0)
    {
        printf("Enter the initialization value: ");
        scanf("%d", &value);
        pa = make_array(size, value);
        if (pa)
        {
            show_array(pa, size);
            free(pa);
        }
        printf("Enter the number of elements (<1 to quit): ");
    }
    printf("Done.\n");
    return 0;
}

// make_array函数:创建数组并初始化
int * make_array(int elem, int val)
{
    int *arr = (int *)malloc(elem * sizeof(int));  // 分配内存空间
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return NULL;
    }
    for (int i = 0; i < elem; i++) {             // 初始化数组的每个元素为指定值
        arr[i] = val;
    }
    
    return arr;
}

// show_array函数:显示数组内容,一行显示8个数
void show_array(const int ar[], int n)
{
    for (int i = 0; i < n; i++) {
        printf("%d ", ar[i]);
        if ((i + 1) % 8 == 0) {         // 每8个元素换行
            printf("\n");
        }
    } 
    if (n % 8 != 0) {                 // 如果最后一行不足8个元素,也换行
        printf("\n");
    }
}

屏幕截图 2025-12-08 140229

  • (9)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    int num_words;
    char **words_array;           // 指向指针的指针,用于存储多个字符串
    char temp_word[100];          // 临时存储单词的数组
    printf("How many words do you wish to enter? ");
    scanf("%d", &num_words);
    while (getchar() != '\n') {      // 跳过换行符
        continue;
    }
    // 为指针数组分配内存
    // 分配num_words个指向char的指针
    words_array = (char **)malloc(num_words * sizeof(char *));
    if (words_array == NULL) {
        printf("Memory allocation failed for words array!\n");
        exit(1);
    }

    printf("Enter %d words now:\n", num_words);
    
    // 读取每个单词
    for (int i = 0; i < num_words; i++) {
        scanf("%s", temp_word);
        
        
        words_array[i] = (char *)malloc((strlen(temp_word) + 1) * sizeof(char));    // 为当前单词分配足够的存储空间
        if (words_array[i] == NULL) {
            printf("Memory allocation failed for word %d!\n", i + 1);
            exit(1);
        }
        
        // 从临时数组复制单词到动态分配的存储空间
        strcpy(words_array[i], temp_word);
    }
  
    printf("Here are your words:\n");         // 显示所有单词
    for (int i = 0; i < num_words; i++) {
        printf("%s\n", words_array[i]);
    }
    
    
    for (int i = 0; i < num_words; i++) {            // 释放分配的内存
        free(words_array[i]);         // 释放每个单词的内存
    }
    free(words_array);            // 释放指针数组的内存
    
    return 0;
}

屏幕截图 2025-12-08 140356

posted @ 2025-12-08 14:34  叶银珍  阅读(5)  评论(0)    收藏  举报