Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c - Make loop stop by pressing dot

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 
  negative numbers are %2.0f", p, n);
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...