簡體   English   中英

創建一個程序,將兩個數字以相等的間隔相除

[英]To create a program that divides two numbers at equal intervals

我做了程序的第一部分,但我不明白動態內存分配和使用指針計算的部分。 我應該編碼什么? 節目內容。

  1. 考慮通過將兩個數字以相等的間隔相除來創建一個數字序列。 例如,如果要創建5個0.0到2.0之間等距的數字,可以將0到2的區間分成4等份(考慮最后的值),每0.5個數字排列。 它變成 0.0, 0.5, 1.0, 1.5, 2.0。
  2. 然后,當您輸入第一個數字、最后一個數字和值的總數時,通過動態內存分配創建一個包含從“第一個數字”到“最后一個數字”等間隔的值的數組,並每個價值都被創造出來。 顯示后,創建一個程序(參見執行示例),該程序也顯示每個值的平方。
  3. “第一個數字”和“最后一個數字”是浮點數,“值的總數”是一個整數。 動態內存分配分配的內存應該是根據“值總數”要求的最小值。 顯示每個值 在第一次顯示時,按原樣輸出存儲在數組中的值。

我的源代碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

    
    int main ()
    {
       int num, i;
       double dfirst, dlast;
       double * x;
    
       / * Enter the first value, the last value, and the number to divide * /
       printf ("Input first, last, total number of x []:");
       scanf ("% lf% lf% d", & dfirst, & dlast, & num);
    
       / * Create after this * /
    
       / * Allocate memory * /
    
      / * Determine the value to store.
         Be careful not to divide by an integer and decide the number of divisions in consideration of the end value * /
    
       / * Display results * /
    
       / * Post-processing * /
       return 0;
    }

執行結果想做什么

% ./a.out
Input first, last, total number of x[]: 0.0  2.0  5
Values of x
0.000 0.500 1.000 1.500 2.000
Values of x^2
0.000 0.250 1.000 2.250 4.000
% ./a.out
Input first, last, total number of x[]: 1.0  2.0  11
Values of x
1.000 1.100 1.200 1.300 1.400 1.500 1.600 1.700 1.800 1.900 2.000
Values of x^2
1.000 1.210 1.440 1.690 1.960 2.250 2.560 2.890 3.240 3.610 4.000

在 C 中,您使用函數malloc動態分配內存。 這個函數是相當低級的,程序員必須非常小心地指定所請求內存的正確大小。 為了使函數更易於使用,可以方便地定義一個也提供錯誤處理的宏:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NEW_ARRAY(ptr, n) \
    (ptr) = malloc((n) * sizeof (ptr)[0]); \
    if ((ptr) == NULL) { \
        fprintf(stderr, "Memory allocation failed: %s\n", strerror(errno)); \
        exit(EXIT_FAILURE); \
    }

宏功能到位后,您只需添加

NEW_ARRAY(x, num);

給你的程序分配一個由num 個元素組成的數組x 當您完成x 時,您可以使用free ( x ) 釋放內存。 在您的程序中,您還需要檢查scanf的結果以確保輸入有效。 祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM