- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 C 编程的新手。我一直在编写这段代码来添加数字,而我只需要这件事的帮助。当我输入字母“q”时,程序应该退出并给出总和。我该怎么做?当前为0号关闭程序。
#include <stdio.h>
int main()
{
printf("Sum Calculator\n");
printf("==============\n");
printf("Enter the numbers you would like to calculate the sum of.\n");
printf("When done, type '0' to output the results and quit.\n");
float sum,num;
do
{
printf("Enter a number:");
scanf("%f",&num);
sum+=num;
}
while (num!=0);
printf("The sum of the numbers is %.6f\n",sum);
return 0;
}
最佳答案
一种方法是将 scanf
行更改为:
if ( 1 != scanf("%f",&num) )
break;
如果他们输入任何无法识别为数字的内容,这将退出循环。
无论您是否采用这种方法,检查 scanf
的返回值并在失败时采取适当的措施仍然是一个好主意。正如您现在所拥有的那样,如果他们输入一些文本而不是数字,那么您的程序将进入无限循环,因为 scanf
会不断失败而不会消耗输入。
关于c - C语言如何输入字母退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30857937/
在C++ Without Fear: A Beginner's Guide That Makes You Feel Smart一书中的第(8)章中,试图显示文本文件的部分代码如下: while(1)
我的这部分作业有效并已完成。尽管我正在努力弄清楚从哪里开始,但我想对此进行补充。我想改变每条线条运动的颜色。例如,如果我按下箭头键,该线将是红色的,或者向右该线将是蓝色的,等等。 我还尝试通过单击字母
我用 C: 编写了这个函数 int process_list(node_t *head){ char c; node_t *prev = head; /* Define pointer
我在 Visual Studio 2013 中用 C# 编写了一个简单的程序。在我的程序结束时,我指示用户: "Please Press Enter to Exit the Program." 我想在
我正在编写一个小的 .jar 应用程序,它要求用户输入一个字符串并将其写入一个 .txt 文件。我感兴趣的是程序在输入字符串不是exit时继续执行以下指令(即写入日期字符串,并将输入字符串写入文本文件
在下面的程序中,我想让代码一直运行,直到用户输入 n 来停止程序。谁能帮我做这个? #include using namespace std; int main() { int i,num,f
我有一个 Java 应用程序。我想指定我的控制台应用程序的“退出代码”。如何为 registerButton 应用退出代码? final JTextField passwordText = new J
我有一个标签,用户将在用户点击按钮后设置数字,数字将存储在数字变量中。在 appdelegate.m 我想访问已设置的号码。例如标签的输入是 9:25这是我所做的。我认为在 appdelegate.m
在表格输出到之后询问用户输入一些小部件。然后您应该计算成本并输出值。如果用户输入‘q’或‘Q’,程序应该终止 我可以使用什么代码来退出程序? 最佳答案 有多种方法可以做到这一点: Applicatio
我是C++初学者,下面的程序很简单,但我不知道为什么当输入“EXIT”时,程序终止了,虽然它应该打印出之前输入的名字! 代码如下: #include #include #include usin
我尝试使用 Unirest.get(...).asObjectAsync(...) 使用计划任务更新资源。要停止使用 Unirest 的程序,您需要调用 Unirest.shutdown(); 以退出
我已经覆盖了登录对话框的 .h 文件中的 closeEvent 函数,以便它在发出时退出程序: void closeEvent(QCloseEvent *event){exit(0)} 但是,
如何在 C# 中使用退出代码退出程序?在 Java 中它将是 System.exit(int code); 最佳答案 或者: 将您的 Main 函数声明为返回 int,并从中返回一个值,或者 调用En
我被困在一个我不知道如何解决的问题上。我正在尝试使用 RandomGenerator 来模拟抛硬币,直到 RandomGenerator 连续抛出 3 个正面,然后程序退出。 变量 flipCount
我对如何实现 System.exit(0); 有点困惑在我的程序中。我想要发生的是用户输入“exit”一词并让程序终止。我还希望程序在输入“clear”时返回“0.0”,但我认为我在处理变量时遇到问题
这是我在程序中用于选项列表的代码。 当然,如果选项数量增加(超过 9),我必须更改 while 条件,采用不同的数字。 我想避免的是使用两位数。 如何让用户按“ESC”键退出程序?或任何其他关键或不同
如果我有一个像这样的简单程序; #include #include using namespace std; int main(){ ofstream output("huh.txt");
我有一个运行多个单元测试的脚本,但是当我按下 control c 时,它只会退出特定的单元测试,而不是整个脚本。有什么办法可以做到这一点?这是我实际执行单元测试的代码。 #bitshift r
我必须创建一个向用户请求非零浮点值的函数;当用户输入0时,打印输入数字的总和。当用户连续输入两个无效输入时,该函数终止。 我有以下代码: def inValues(): counter = 0
我正在尝试完成一个简单的 GUI 自动化程序,该程序仅打开一个网页,然后每 0.2 秒单击一次页面上的特定位置,直到我告诉它停止。我希望我的代码运行并使其循环无限运行,直到我指定的键绑定(bind)打
我是一名优秀的程序员,十分优秀!