基本上在我的程式中,我使用了一個 for 回圈,它將值分配給陣列的每個元素并將它們存盤在其中,然后將它們寫出來,它給出了很好的結果。但是,當我退出回圈并想寫出這個陣列的元素時,我得到的錯誤結果都等于 0.0000。我該如何克服這個問題并將結果保持在 for 回圈之外?
// declares arrays of the given size
double array[50];
// I calculate the length of the array using sizeof
double array_lenght = sizeof(array) / sizeof(array[0]);
printf("%lf \n", array_lenght);
//declares two variables of type double one for the area over which it will generate x the other for incrementing the deltaX difference
double length;
double deltaX;
// I count the differences of the domains and the value of one sample for x and display it
length = Dmax - Dmin;
deltaX = length / 50;
printf("Delta x = %lf \n", deltaX);
double i;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
int k = 0;
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
printf("Elements of original array: \n");
for (int i = 0; i < array_length; i ) {
printf("%lf ", array[i]);
}
uj5u.com熱心網友回復:
您一遍又一遍地寫入相同的陣列元素(元素 0):
double i;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
int k = 0;
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
在每次回圈迭代中k設定k為的初始化程式。0只需將其移出回圈即可:
double i;
int k = 0;
for(i = Dmin; i < Dmax; i =deltaX)
{
// assigns to each element in the array the value of x increased by delta x and stores them in my array.
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
這樣,它將按預期逐步遍歷陣列。
uj5u.com熱心網友回復:
我認為您放錯了 k 宣告。
double i;
int k = 0; // <--- moved outside of the loop
for(i = Dmin; i < Dmax; i =deltaX)
{
//int k = 0; <--- keeps resetting k
array[k] = i;
double y = A * cos(i/B) C * sin(i) D;
printf("For a sample of %lf, the assigned function is %lf \n", array[k], y);
k ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523657.html
標籤:C
上一篇:C中指向陣列的指標
