c - 循环出错了
问题描述
我是 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;
}
解决方案
你必须scanf
像这样添加一个空格scanf (" %c",&opsi);
,否则你会被\n
当作你的角色scanf
。
另请注意,您正在使用未初始化的变量n1
和hasil_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;
}
推荐阅读
- r - 如何在使用 enquo() 的函数上使用 purrr::invoke_map()?
- xml - 如何从 XML 文档 (VB.NET) 中获取值
- java - Retrofit2 异步下载数据并获得进度条
- python - 如何在烧瓶 python 应用程序中执行 curl POST 命令
- python-3.x - Pandas - 使用 .apply(pd.to_datetime) 时排除时区
- tensorflow - 自定义 tensorflow 矛盾的 AVX2/FMA 消息?
- php - 无法使用 php 和 url 填充表单输入
- http - Redmine 会议预订插件返回 422 Unprocessable Entity
- java - 如何防止vaadin组件调整大小?
- sql - 来自一列的 SQL UPDATE 数据与来自另一列的匹配