How to add a loop counter and respond to user input

조회 수: 3 (최근 30일)
Chris
Chris 2013년 6월 11일
Write a program that repeats the process of prompting the user to enter a positive number as long as the user correctly enters positive numbers when prompted. The program should count the number of numbers that the user successfully enters. As soon as the user types a negative number the program will print OK and shows the number of numbers that the user has successfully entered.
  댓글 수: 2
Chris
Chris 2013년 6월 11일
편집: Azzi Abdelmalek 2013년 6월 11일
I already have this much.
a=10;
while a-1>0
a=input('Please input an even number [even]: ', 's')
end
Walter Roberson
Walter Roberson 2013년 6월 11일
편집: Walter Roberson 2013년 6월 11일
Why are you asking the user to enter even numbers when the homework requires entering positive numbers?
You are not checking to see whether the input is acceptable or not.
What should happen if the user enters 0? 0 is not positive, but it is also not negative (the termination condition)

댓글을 달려면 로그인하십시오.

답변 (2개)

Vishal Rane
Vishal Rane 2013년 6월 11일
When in doubt write a pseudo code:
1) Prompt user to enter something ( in ur case a number )
2) Accept number from user
3) Code checks if number is acceptable ( check for special chars, strings, etc)
4a) If valid number and positive, store it, repeat 1-4
4b) If valid number and negative, display 'OK', calculate and display count of stored numbers
4c) If invalid input, show prompt again ignoring user input or notifying him/her of the same

Chetan Aswathanarayana
Chetan Aswathanarayana 2013년 6월 20일
function Sample()
Loop = true;
Count = 0;
while(Loop)
a = input('Please input a positive number: ');
if a>=0
Count = Count+1;
else
Loop = false;
end
end
fprintf('Ok, the number of inputs enetered by the user is %d',Count);
end

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by