我只是学习c而且我正在做一个例外情况,我必须在1-99.99内打印10 x 4数字表,只打印大于67的数字,然后打印每行的平均值。但是我的代码不会编译,我不知道为什么。这就是我所拥有的
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
int main(void)
{
int r;
int c;
double num;
double sum;
int count;
double avg;
for(c = 0; c < 10; c++)
{
avg = 0;
sum = 0;
count = 0;
for(r = 1; r< 5; r++)
{
num = (float) N * rand() / (RAND_MAX + 1.0);
if (num > 67.0)
count = count + 1;
sum = sum + num;
printf("%.2f, " num);
else
printf("%4s");
}
if(count = 0)
continue;
avg = (sum\count);
printf("%.2f |", avg);
printf("\n\n");
}
}
我收到以下错误
line 24 expected '<' before num
line 25 else without a previous if statement
line 31 stray '\' in program
line 31 expected'>' before count
我看了看他们但我不能把它们弄清楚?
答案 0 :(得分:2)
您需要替换avg = (sum/count);
。您还应该更改为if(count == 0)
。你错过了一些花括号。
建议更改:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
int main(void)
{
int r;
int c;
double num;
double sum;
int count;
double avg;
for(c = 0; c < 10; c++) {
avg = 0;
sum = 0;
count = 0;
for(r = 1; r< 5; r++) {
num = (float) N * rand() / (RAND_MAX + 1.0);
if (num > 67.0) {
count = count + 1;
sum = sum + num;
printf("%.2f, ", num);
}
else
printf("%4s");
}
if(count = 0)
continue;
avg = (sum/count);
printf("%.2f |\n\n", avg);
}
}
答案 1 :(得分:1)
你需要将if
身体放在花括号中:
if (num > 67.0) {
count = count + 1;
sum = sum + num;
printf("%.2f, " num);
}
else {
printf("%4s");
}
同样改变:
avg = (sum\count);
为:
avg = (sum/count);
为了比较相等,我们使用==
而非=
:
if(count == 0)
还用逗号分隔printf
个参数:
printf("%.2f, ", num);
答案 2 :(得分:0)
我没有运行它,但它现在编译,它需要;
1)第24行,
:printf("%.2f, ", num)
,
2)支持if,从第21行开始:
if (num > 67.0) {
count = count + 1;
sum = sum + num;
printf("%.2f, ", num);
}
3)除法是/
而不是\
。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
int main(void)
{
int r;
int c;
double num;
double sum;
int count;
double avg;
for(c = 0; c < 10; c++)
{
avg = 0;
sum = 0;
count = 0;
for(r = 1; r< 5; r++)
{
num = (float) N * rand() / (RAND_MAX + 1.0);
if (num > 67.0) {
count = count + 1;
sum = sum + num;
printf("%.2f, ", num);
}
else
printf("%4s");
}
if(count = 0)
continue;
avg = (sum/count);
printf("%.2f |", avg);
printf("\n\n");
}
}