[問題] 練習for與while遇到的問題
最近開始自學C,在練習書上的習題時遇到一個問題
題目要求從檔案讀入數據,再分別用for及while輸出到螢幕上
讀入的數據格式如下(.txt):
10 5
3
4
5
6
7
10 10
3
4
5
6
7
我先用for寫了以下程式:
#include <stdio.h>
void main(void)
{
int n,i;
double s,v,a,t;
FILE *inptr;
inptr=fopen("DISTANCE.txt","r");
printf(" Car under constant acceleration \n"
"Initial \n"
"Velocity time acceleration distance\n"
"_________________________________________\n\n");
for(i=1;i<=2;i++)
{
fscanf(inptr,"%lf %lf",&v,&t);
for(n=1;n<=5;n++)
{
fscanf(inptr,"%lf",&a);
s=v*t+0.5*a*t*t;
if (n==1) printf("%3.0lf %10.0lf %10.0lf %14.2lf\n",v,t,a,s);
else printf("%25.0lf %14.2lf\n",a,s);
}
}
fclose(inptr);
}
可正確輸出題目要求格式如下:
Car under constant acceleration
Initial
Velocity time acceleration distance
_________________________________________
10 5 3 87.50
4 100.00
5 112.50
6 125.00
7 137.50
10 10 3 250.00
4 300.00
5 350.00
6 400.00
7 450.00
接下來用while寫的程式如下:
#include <stdio.h>
void main(void)
{
int n=1,i=1;
double s,v,a,t;
FILE *inptr;
inptr=fopen("DISTANCE.txt","r");
printf(" Car under constant acceleration \n"
"Initial \n"
"Velocity time acceleration distance\n"
"_________________________________________\n\n");
while(i<=2)
{
fscanf(inptr,"%lf %lf",&v,&t);
while(n<=5)
{
fscanf(inptr,"%lf",&a);
s=v*t+0.5*a*t*t;
if (n==1) printf("%3.0lf %10.0lf %10.0lf %14.2lf\n",v,t,a,s);
else printf("%25.0lf %14.2lf\n",a,s);
n++;
}
i++;
}
fclose(inptr);
}
可是卻只輸出了一半的數據如下:
Car under constant acceleration
Initial
Velocity time acceleration distance
_________________________________________
10 5 3 87.50
4 100.00
5 112.50
6 125.00
7 137.50
請問我的while程式中有哪邊沒注意到寫錯的嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.240.94.15
推
06/14 18:35, , 1F
06/14 18:35, 1F
→
06/14 18:40, , 2F
06/14 18:40, 2F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章