gpt4 book ai didi

c - 按点使循环停止

转载 作者:行者123 更新时间:2023-11-30 20:24:25 24 4
gpt4 key购买 nike

我需要编写一个程序,要求您输入数字,当您按点时,它将结束循环并显示有多少数字是正数和多少数字是负数,例如 4 5 -9 。

程序应该显示 2 个正数和 1 个负数,但这不是我的问题。我陷入了当我按点时循环应该停止的部分,请记住我们正处于编程的初级阶段,所以我不能使用花哨的东西。

正如您在这里所看到的,我尝试为变量提供两种类型(charfloat),但我认为这不起作用,因为它使用字符的值而不是数字本身。

int main()
{
float p, n;
char a;

n = 0;
p = 0;

do
{
printf("type a number");
scanf("%s&%f", &a);

if (a < 0)
{
n = n + 1;
}
else if (a > 0)
{
p = p + 1;
}
else
{
}
}
while (a != '.');

printf(" positive numbers are %2.0f \n negative numbers are %2.0f", p, n);
return 0;
}

最佳答案

通过流行的在线 C 编译器运行您的代码:

http://www.tutorialspoint.com/compile_c_online.php

您的代码按预期运行。当你输入“.”时会发生什么?

编辑:(解决方案)

问题是当你输入负数时,

a = '-'

其整数值大于零,因此不会触发负面情况。

解决方案是检查负号:

if (a == '-') {...}

另外,请注意“.”输入的终止循环被计为正数。

关于c - 按点使循环停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33577920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com