由pressing点使循环停止 [英] Make loop stop by pressing dot

查看:171
本文介绍了由pressing点使循环停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个程序,要求你输入数字,当你preSS点就结束循环,并显示有多少数字是积极的,有多少是负面的,例如像4 5 -9。

该计划应显示2个数字为正,1为负,但是这不是我的问题。我被困在那里的部分环路应该停止的时候我preSS点,并牢记我们是在编程首发年龄,所以我可以不使用花哨的东西。

正如你可以在这里看到我试着给一个变量两类(字符浮动),但没有按' ŧ的工作,我想是因为它使用的字符而不是数字本身的价值。

  INT的main()
{
    浮P,N;
    所以char a;    N = 0;
    p值= 0;    做
    {
        的printf(请键入数字);
        scanf函数(%S&放大器;%F,&安培; A);        如果(一个℃,)
        {
            N = N + 1;
        }
        否则如果(一个大于0)
        {
            P = P + 1;
        }
        其他
        {
        }
    }
    而(一个!='。');    的printf(正数是%2.0F \\ n负数均%2.0F,P,N);
    返回0;
}


解决方案

通过网上流行的C编译器运行在这里您code:

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

您code跑了预期。当你输入时会发生什么。?

编辑:(解决方案)

的问题是,当用户输入一个负数,

  A =' - '

其具有一个整数值大于零,因此,没有触发否定的情况下

该解决方案的话,是检查的负号:

 如果(A ==' - '){...}

此外,请注意,。输入到终止循环被算作一个正数。

I need to write a program that asks you to enter numbers and when you press dot it will end the loop and display how many numbers are positive and how many are negative, like for example 4 5 -9 .

The program should show 2 numbers are positive and 1 is negative, but that isn't my problem. I'm stuck at the part where the loop should stop when I press dot, and bear in mind we are at the starter ages of programming so I can't be using fancy stuff.

As you can see here I tried giving a variable two types (char and float) but that doesn't work I think because it uses the value of the character instead of the numbers themselves.

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;
}

解决方案

Running your code through the popular online c compiler here:

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

Your code ran as expected. What happens when you type "."?

EDIT: (Solution)

The problem was that when you input a negative number,

a = '-'

which has an integer value greater than zero, hence not triggering the negative case.

The solution then, is to check for the negative sign:

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

Also, note that the '.' entered to terminate the loop is being counted as a positive number.

这篇关于由pressing点使循环停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆