首页 > 解决方案 > 循环出错了

问题描述

我是 C 的新手。我的问题是代码一直在该行循环(您可以检查代码),而我想要的是它循环整个 for 语句,而不是单行。

英语不是我的第一语言,所以我真的很抱歉

#include <stdio.h>
int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw;
char opsi;
int main (void) {
    int n1; //Homework
    int c1;
    for (c1=0;opsi != 'n';c1++) {
      printf ("Input : ");
      scanf ("%d",&hw);
      n1 += 1;
      hasil_hw += hw;
      printf ("\nInput another marks? (y/n)"); // it loops here when it run
      scanf ("%c",&opsi);
    }
 return 0;
}

标签: c

解决方案


你必须scanf像这样添加一个空格scanf (" %c",&opsi);,否则你会被\n当作你的角色scanf

另请注意,您正在使用未初始化的变量n1hasil_hw. 你必须在你的代码中添加n1=0和。hasil_hw=0

也如评论中所述,您应该检查scanf返回值。

int hw;
int uts;
int uas;
float hasil_uts;
float hasil_uas;
float hasil_hw=0;
char opsi;
int main(void) {
    int n1=0; //Homework
    int c1;
    for (c1 = 0; opsi != 'n'; c1++) {
        printf("Input : ");
        if ( scanf("%d", &hw) != 1) 
      { 
         fputs ("error: invalid value.\n", stderr); 
          return 1;
      }
        n1 += 1;
        hasil_hw += hw;
        printf("\nInput another marks? (y/n)"); // it loops here when it run
        if (scanf(" %c", &opsi) != 1)//add space before %c 
      { 
         fputs ("error: invalid value.\n", stderr); 
          return 1;
      }
    }
    return 0;
}

推荐阅读