[英]Using arrays in C
我有一個令人不安的家庭作業任務,並希望指向正確的方向。
任務是開發一個C程序,完成以下任務:
main()
,創建一個名為qqqqq的二維數組,它可以容納48個整數(6行,8列) qqqqq
。 main
在哪里開始?
這是我到目前為止:
int main (void)
{
int qqqqq [6] [8];
int r;
int c;
srandom ((unsiged) time (NULL));
for (r=0; r <=6; r++)
{
for(c=0; c <=8; c++)
{
qqqqq[r][c] = random ( )
接下來我該怎么辦?
我感謝任何幫助或指導。
謝謝 - 詹姆斯
以下是我將如何解決這個問題:
算法是解決問題所需的一組步驟。 手頭的任務已經描述了問題,但通常用自己的話重新編寫它是一種好習慣。 (作為一個實際觀點,您可以將您的話語傳達給您的客戶 - 在這種情況下,您的老師 - 並確認您對問題的理解是正確的。)
假設:不打印任何總和。 (例如,列總和的總和。)
谷歌在這里很有幫助。 嘗試Google搜索:
generate random integers C
你會發現很多幫助,特別是有關rand()
函數的提示。 修改Google搜索:
generate random integers C rand()
此搜索找到了一個很好的資源: http : //www.cplusplus.com/reference/clibrary/cstdlib/rand/
同樣,Google搜索可以在此處提供幫助:
print information on the screen in C
這得到: http : //www.daniweb.com/software-development/c/threads/9688
printf
函數似乎很方便。 了解更多信息:
printf C
這產生了一個熟悉的網站: http : //www.cplusplus.com/reference/clibrary/cstdio/printf/
如果你真的想“哇”你的教授:
r
和c
可能代表行和列,但是對於拼出row
和column
花費的時間,它將保存讀取代碼的任何人不必猜測或讀取代碼以發現它的真實用途。 qqqqq
可以使用更好的名字。 建議一個,甚至。 例如:
#include <stdio.h>
/* Subject to change; only change it in one spot. */
#define MAX_ROWS 6
#define MAX_COLS 8
#define MIN_RANDOM_NUMBER 1
#define MAX_RANDOM_NUMBER 15
/** Returns a number between MIN_RANDOM_NUMBER and MAX_RANDOM_NUMBER. */
int randomNumber() {
return 0; /* FIX ME to use rand() and the modulus operator. */
}
int main( int argc, char *argv[] ) {
int qqqqq[MAX_ROWS][MAX_COLS];
/* FIX ME: Move these variables into the display function. */
int sumRows = 0;
int sumCols = 0;
/* Use different random numbers each time the program runs. */
seedRandomNumber();
/* Initialize the array with random numbers. */
for( int row = 0; row < MAX_ROWS; row++ ) {
for( int col = 0; col < MAX_COLS; col++ ) {
qqqqq[row][col] = randomNumber();
}
}
/* Display the array to the screen along with the sum totals. */
display( qqqqq );
}
請注意,您可以選擇。
您可以將sumRows
變量傳遞給display
函數,或者您可以編寫display
函數來調用calculateSumRows
本身。 我的偏好是始終簡化函數原型。 也就是說,減少參數的數量。 它使未來的變化更容易。
所以寫display
為:
void display( int randomValues[MAX_ROWS][MAX_COLS] ) {
int sumCols = 0;
for( int row = 0; row < MAX_ROWS; row++ ) {
/* FIX ME: Write the calculateSumCols function. */
sumCols = calculateSumCols( randomValues, row );
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value at this row/column. */
}
}
/* FIX ME: Use printf here to display sumRows. */
for( int col = 0; col < MAX_COLS; col++ ) {
/* FIX ME: Use printf here to display the value of the rows. */
printf( "%d ", calculateSumRows( randomValues, col ) );
}
}
這應該讓你開始。
請注意,您可以在此處進行一些簡化和優化。 忘記他們。 獲取代碼,使其真正起作用。 代碼工作后,保存它。 甚至可以制作備份副本。
然后開始改變它。 看看你是否可以刪除變量。 也許你甚至可以刪除一些for
循環。 如果您犯了錯誤,您可以隨時參考備份副本。 最終,您的“備份”副本將成為“源代碼存儲庫”。
這是一個非常好的開始! 但請注意,維數X的數組的有效索引為0 ...(X-1)。 你的循環應該是這樣的
for (r=0; r <6; r++)
(注意“<6”而不是“<= 6”。
現在你需要另一個數組來保存行總數,還有一個數組來保存列總數,然后再需要一些循環來計算它們並將它們存儲在數組中。
一些關鍵的事情:
有6行8列,每個都需要總計。 首先將更多數組作為存儲這些總數的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.