所以我正在研究一個C代碼,它將接受用戶輸入(以存款金額的形式[如銀行]和存款的保留時間),並提出一個「利率「,或者更簡單地說,只是一個十進制數。我不知道爲什麼它不會工作。它應該讀取一個文件到一個數組中,並根據該數組進行計算。當我說它不起作用時,它將在表格中讀取,詢問用戶輸入,但無論用戶輸入如何,它都會輸出0。只有當用戶輸入'none'時才能退出。 下面的代碼:變量和/或數組問題
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
FILE *unit2;
int main()
{
int month[14];
float num1[14];
float num2[14];
float num3[14];
float numin1, numin2, numin3;
char input[100];
int time;
float amount;
float output = 0;
int numin;
int i, j;
int nret;
unit2 = fopen("units2.txt", "r");
printf("Months\t\t\t Interest\n");
while(!(feof(unit2)))
{
i = 0;
nret = fscanf(unit2, "%d %f %f %f", &numin, &numin1, &numin2, &numin3);
if(nret == EOF)
break;
month[i] = numin;
num1[i] = numin1;
num2[i] = numin2;
num3[i] = numin3;
printf(" %d\t\t%1.2f %1.2f %1.2f %1.2f %1.2f %1.2f\n", numin, numin1, numin1, numin2, numin2, numin3, numin3);
i++;
}
printf("\nEnter your deposit amount, followed by the duration in months. Or, type 'none' to exit.\n");
gets(input);
sscanf(input, "%f %d", &amount, &time);
if(!strcmp(input, "none")){
printf("\nCome back later!\n");
exit(0);
}
if(time <= 0){
printf("Please enter a larger amount of months.\n");
}
if(time >= 120){
printf("Please enter a smaller amount of months\n");
}
if(amount <= 999){
printf("Please enter a larger deposit.\n");
}
j = 0;
while(time != month[j]){
j++;
}
if(amount >= 1000 && amount <= 9999){
output = num1[j];
}
else if(amount >= 10000 && amount <= 99999){
output = num2[j];
}
else if(amount >= 100000){
output = num3[j];
}
printf("Your interest rate will be %f.\n", output);
}
而且程序讀取該文件有下列圖表:
1 - 0.02 0.03 0.05
2 - 0.02 0.03 0.05
3 - 0.02 0.05 0.10
6 - 0.05 0.10 0.15
9 - 0.05 0.10 0.15
12 - 0.05 0.15 0.20
18 - 0.15 0.25 0.30
21 - 0.15 0.25 0.30
24 - 0.15 0.25 0.30
30 - 0.15 0.25 0.30
36 - 0.15 0.35 0.40
48 - 0.25 0.45 0.50
60 - 0.35 0.55 0.60
84 - 0.35 0.55 0.60
好吧,我想通了。首先,i = 0在循環中,導致它重複(感謝rmartinjak)。另一部分是我有:
while(time < month[j]){
j++;
}
這使得它會繼續增加j,即使是過去的時間。 所以我簡單地改變了 '<' 到 '>':
while(time > month[j]{ \\so it will stop when at time.
j++;
}
和我從線像這樣除去 '=':
if(amount >= 1000 && amount <= 9999){
這樣:
if(amount > 1000 && amount < 9999){
現在一切似乎都很好。再次感謝大家的幫助!
「不起作用」不是一個好的錯誤描述。 –
好的,所以當我說它不起作用時,它會在表格中讀取,詢問用戶輸入,但是它會輸出0,不受用戶輸入的影響。只有當用戶輸入'none'時才能退出。 – user3287431
請閱讀['while(!feof(file))'總是錯的](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong)。請注意,scanf()將在讀取所有字段失敗時返回小於4的數字。一個問題是你實際上沒有讀取數據,因爲你的'scanf()'字符串不能處理被空格包圍的'-'。你應該檢查'if(scanf(...)!= 4)'來更好地覆蓋錯誤情況。調試時,最基本的技巧是打印您閱讀的數據,以確保您實際閱讀您認爲正在閱讀的內容。 (循環中的'i = 0'也是錯誤的。) –